Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display certificate Info (#1) #91

Merged
merged 15 commits into from
Jul 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions db/patch2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
BEGIN TRANSACTION;

CREATE TABLE monitor_tls_info (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
monitor_id INTEGER NOT NULL,
info_json TEXT
);

COMMIT;
2 changes: 1 addition & 1 deletion server/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Database {

static templatePath = "./db/kuma.db"
static path = './data/kuma.db';
static latestVersion = 1;
static latestVersion = 2;
static noReject = true;

static async patch() {
Expand Down
63 changes: 59 additions & 4 deletions server/model/monitor.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@

const https = require('https');
const dayjs = require("dayjs");
const utc = require('dayjs/plugin/utc')
var timezone = require('dayjs/plugin/timezone')
dayjs.extend(utc)
dayjs.extend(timezone)
const axios = require("axios");
const {UP, DOWN, PENDING} = require("../util");
const {tcping, ping} = require("../util-server");
const {debug, UP, DOWN, PENDING} = require("../util");
const {tcping, ping, checkCertificate} = require("../util-server");
const {R} = require("redbean-node");
const {BeanModel} = require("redbean-node/dist/bean-model");
const {Notification} = require("../notification")

// Use Custom agent to disable session reuse
// https://github.com/nodejs/node/issues/3940
const customAgent = new https.Agent({
maxCachedSessions: 0
});

/**
* status:
* 0 = DOWN
Expand Down Expand Up @@ -75,11 +82,25 @@ class Monitor extends BeanModel {
if (this.type === "http" || this.type === "keyword") {
let startTime = dayjs().valueOf();
let res = await axios.get(this.url, {
headers: { 'User-Agent':'Uptime-Kuma' }
})
headers: { "User-Agent": "Uptime-Kuma" },
httpsAgent: customAgent,
});
bean.msg = `${res.status} - ${res.statusText}`
bean.ping = dayjs().valueOf() - startTime;

// Check certificate if https is used

let certInfoStartTime = dayjs().valueOf();
if (this.getUrl()?.protocol === "https:") {
try {
await this.updateTlsInfo(checkCertificate(res));
} catch (e) {
console.error(e.message)
}
}

debug("Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms")

if (this.type === "http") {
bean.status = UP;
} else {
Expand Down Expand Up @@ -194,10 +215,35 @@ class Monitor extends BeanModel {
clearInterval(this.heartbeatInterval)
}

// Helper Method:
// returns URL object for further usage
// returns null if url is invalid
getUrl() {
try {
return new URL(this.url);
} catch (_) {
return null;
}
}

// Store TLS info to database
async updateTlsInfo(checkCertificateResult) {
let tls_info_bean = await R.findOne("monitor_tls_info", "monitor_id = ?", [
this.id
]);
if (tls_info_bean == null) {
tls_info_bean = R.dispense("monitor_tls_info");
tls_info_bean.monitor_id = this.id;
}
tls_info_bean.info_json = JSON.stringify(checkCertificateResult);
await R.store(tls_info_bean);
}

static async sendStats(io, monitorID, userID) {
Monitor.sendAvgPing(24, io, monitorID, userID);
Monitor.sendUptime(24, io, monitorID, userID);
Monitor.sendUptime(24 * 30, io, monitorID, userID);
Monitor.sendCertInfo(io, monitorID, userID);
}

/**
Expand All @@ -218,6 +264,15 @@ class Monitor extends BeanModel {
io.to(userID).emit("avgPing", monitorID, avgPing);
}

static async sendCertInfo(io, monitorID, userID) {
let tls_info = await R.findOne("monitor_tls_info", "monitor_id = ?", [
monitorID
]);
if (tls_info != null) {
io.to(userID).emit("certInfo", monitorID, tls_info.info_json);
}
}

/**
* Uptime with calculation
* Calculation based on:
Expand Down
49 changes: 49 additions & 0 deletions server/util-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,52 @@ exports.getSettings = async function (type) {

return result;
}


// ssl-checker by @dyaa
// param: res - response object from axios
// return an object containing the certificate information

const getDaysBetween = (validFrom, validTo) =>
Math.round(Math.abs(+validFrom - +validTo) / 8.64e7);

const getDaysRemaining = (validFrom, validTo) => {
const daysRemaining = getDaysBetween(validFrom, validTo);
if (new Date(validTo).getTime() < new Date().getTime()) {
return -daysRemaining;
}
return daysRemaining;
};

exports.checkCertificate = function (res) {
const {
valid_from,
valid_to,
subjectaltname,
issuer,
fingerprint,
} = res.request.res.socket.getPeerCertificate(false);

if (!valid_from || !valid_to || !subjectaltname) {
throw { message: 'No TLS certificate in response' };
}

const valid = res.request.res.socket.authorized || false;

const validTo = new Date(valid_to);

const validFor = subjectaltname
.replace(/DNS:|IP Address:/g, "")
.split(", ");

const daysRemaining = getDaysRemaining(new Date(), validTo);

return {
valid,
validFor,
validTo,
daysRemaining,
issuer,
fingerprint,
};
}
6 changes: 6 additions & 0 deletions server/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@ exports.ucfirst = function (str) {
return firstLetter.toUpperCase() + str.substr(1);
}

exports.debug = (msg) => {
if (process.env.NODE_ENV === "development") {
console.log(msg)
}
}

15 changes: 13 additions & 2 deletions src/components/Datetime.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,23 @@ dayjs.extend(relativeTime)
export default {
props: {
value: String,
dateOnly: {
type: Boolean,
default: false,
},
},

computed: {
displayText() {
let format = "YYYY-MM-DD HH:mm:ss";
return dayjs.utc(this.value).tz(this.$root.timezone).format(format)
if (this.value !== undefined && this.value !== "") {
let format = "YYYY-MM-DD HH:mm:ss";
if (this.dateOnly) {
format = "YYYY-MM-DD";
}
return dayjs.utc(this.value).tz(this.$root.timezone).format(format);
} else {
return "";
}
},
}
}
Expand Down
17 changes: 16 additions & 1 deletion src/mixins/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default {
importantHeartbeatList: { },
avgPingList: { },
uptimeList: { },
certInfoList: {},
notificationList: [],
windowWidth: window.innerWidth,
showListMobile: false,
Expand Down Expand Up @@ -58,7 +59,17 @@ export default {
this.$router.push("/setup")
});

socket.on('monitorList', (data) => {
socket.on("monitorList", (data) => {
// Add Helper function
Object.entries(data).forEach(([monitorID, monitor]) => {
monitor.getUrl = () => {
try {
return new URL(monitor.url);
} catch (_) {
return null;
}
};
});
this.monitorList = data;
});

Expand Down Expand Up @@ -114,6 +125,10 @@ export default {
this.uptimeList[`${monitorID}_${type}`] = data
});

socket.on('certInfo', (monitorID, data) => {
this.certInfoList[monitorID] = JSON.parse(data)
});

socket.on('importantHeartbeatList', (monitorID, data) => {
if (! (monitorID in this.importantHeartbeatList)) {
this.importantHeartbeatList[monitorID] = data;
Expand Down
61 changes: 61 additions & 0 deletions src/pages/Details.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,46 @@
<p>(30-day)</p>
<span class="num"><Uptime :monitor="monitor" type="720" /></span>
</div>

<div class="col" v-if="certInfo">
<h4>CertExp.</h4>
<p>(<Datetime :value="certInfo.validTo" date-only />)</p>
<span class="num" >
<a href="#" @click.prevent="toggleCertInfoBox = !toggleCertInfoBox">{{certInfo.daysRemaining}} days</a>
</span>
</div>
</div>
</div>

<div class="shadow-box big-padding text-center" v-if="showCertInfoBox">
<div class="row">
<div class="col">
<h4>Certificate Info</h4>
<table class="text-start">
<tbody>
<tr class="my-3">
<td class="px-3">Valid: </td>
<td>{{ certInfo.valid }}</td>
</tr>
<tr class="my-3">
<td class="px-3">Valid To: </td>
<td><Datetime :value="certInfo.validTo" /></td>
</tr>
<tr class="my-3">
<td class="px-3">Days Remaining: </td>
<td>{{ certInfo.daysRemaining }}</td>
</tr>
<tr class="my-3">
<td class="px-3">Issuer: </td>
<td>{{ certInfo.issuer }}</td>
</tr>
<tr class="my-3">
<td class="px-3">Fingerprint: </td>
<td>{{ certInfo.fingerprint }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

Expand Down Expand Up @@ -122,6 +162,7 @@ export default {
page: 1,
perPage: 25,
heartBeatList: [],
toggleCertInfoBox: false,
}
},
computed: {
Expand Down Expand Up @@ -180,6 +221,18 @@ export default {
}
},

certInfo() {
if (this.$root.certInfoList[this.monitor.id]) {
return this.$root.certInfoList[this.monitor.id]
} else {
return null
}
},

showCertInfoBox() {
return this.certInfo != null && this.toggleCertInfoBox;
},

displayedRecords() {
const startIndex = this.perPage * (this.page - 1);
const endIndex = startIndex + this.perPage;
Expand Down Expand Up @@ -268,4 +321,12 @@ table {
font-size: 13px;
color: #AAA;
}

.stats {
padding: 10px;

.col {
margin: 20px 0;
}
}
</style>