import fs, { writeFile, unlink, symlink } from 'fs-extra'; import axios from 'axios'; import { randomBytes } from 'crypto'; import { Message, MessageEmbed, TextChannel } from 'discord.js'; import { AccountInterface } from '../models'; import { Client, Command } from '../class'; import { parseCertificate } from '../functions'; export default class CWG_SelfService extends Command { public urlRegex: RegExp; constructor(client: Client) { super(client); this.name = 'selfserv'; this.description = 'Creates a subdomain on your account. Do not include the entire subdomain: if you want `mydomain.cloud.libraryofcode.org`, just supply `mydomain` in the command parameters.\nYou must receive an authentication token from the Instant Application Service, see `?apply` for more information.'; this.usage = `${this.client.config.prefix}cwg selfserv `; this.aliases = ['ss']; this.enabled = true; this.urlRegex = /^[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]+$/; } public async run(message: Message, args: string[]) { const reqDomain = `${escape(args[0])}.cloud.libraryofcode.org`; try { if (!args[1]) return this.client.commands.get('help').run(message, ['cwg', this.name]); const account = await this.client.db.Account.findOne({ userID: message.author.id }); if (!account) return this.error(message.channel, 'Cannot locate account.'); if (!this.checkAuthorizationToken(message.author.id, args[1])) return this.error(message.channel, 'The authentication token provided is invalid.'); if (!this.domainTextValidation(args[0])) return this.error(message.channel, 'Invalid domain.'); if (await this.client.db.Domain.exists({ domain: reqDomain })) return this.error(message.channel, 'This domain already exists.'); const edit = await this.loading(message.channel, 'Binding domain...'); const certs: { cert?: string, key?: string } = {}; certs.cert = await fs.readFile('/etc/ssl/private/cloud-libraryofcode-org.chain.crt', { encoding: 'utf8' }); certs.key = await fs.readFile('/etc/ssl/private/cloud-libraryofcode-org.key', { encoding: 'utf8' }); let port: number; try { port = await this.getPort(); } catch { return this.error(message.channel, 'Unable to acquire port automatically. Please contact a Technician.'); } const domain = await this.createDomain(account, reqDomain, port, certs); const tasks = [message.delete(), this.client.util.exec('systemctl reload nginx')]; // @ts-ignore await Promise.all(tasks); const embed = new MessageEmbed() .setTitle('Domain Creation') .setColor(3066993) .addField('Account Username', `${account.username} | <@${account.userID}>`, true) .addField('Technician', 'SYSTEM', true) .addField('Domain', domain.domain, true) .addField('Port', String(domain.port), true); const certPath = `/opt/CloudServices/temp/${randomBytes(5).toString('hex')}`; await writeFile(certPath, certs.cert, { encoding: 'utf8' }); const cert = await parseCertificate(this.client, certPath); embed.addField('Certificate Issuer', cert.issuer.organizationName, true) .addField('Certificate Subject', cert.subject.commonName, true) .setFooter(this.client.user.username, this.client.user.avatarURL()) .setTimestamp(new Date(message.createdTimestamp)); const completed = [ edit.edit(`***${this.client.stores.emojis.success} Your subdomain has been create, please check your DMs or email address for more information.`), (this.client.channels.cache.get('580950455581147146') as TextChannel).send({ embeds: [embed] }), this.client.users.fetch(account.userID).then((r) => r.send({ embeds: [embed] })), this.client.util.transport.sendMail({ to: account.emailAddress, from: 'Library of Code sp-us | Support Team ', replyTo: 'Dept of Engineering ', subject: 'Your domain has been created', html: `

Library of Code sp-us | Cloud Services

Hello, this is an email informing you that a new domain under your account has been bound. Information is below.

Domain: ${domain.domain}
Port: ${domain.port}
Certificate Issuer: ${cert.issuer.organizationName}
Certificate Subject: ${cert.subject.commonName}
Responsible Engineer: SYSTEM

If you have any questions about additional setup, you can reply to this email or send a message in #cloud-support in our Discord server.
Library of Code sp-us | Support Team `, }), ]; return Promise.all(completed); } catch (err) { this.client.util.handleError(err, message, this); const tasks = [fs.unlink(`/etc/nginx/sites-enabled/${reqDomain}`), fs.unlink(`/etc/nginx/sites-available/${reqDomain}`), this.client.db.Domain.deleteMany({ domain: reqDomain })]; return Promise.allSettled(tasks); } } public async getPort() { const port = Number(await this.client.redis.get('cwgsspc')); if (await this.client.db.Domain.exists({ port })) throw new Error('Error retreiving port.'); if (port >= Number(process.env.MAX_CWG_PORT)) throw new Error('Error retrieving port.'); await this.client.redis.incr('cwgsspc'); return port; } public domainTextValidation(domain: string) { if (!this.urlRegex.test(domain)) return false; if (/[^\w\s-]/.test(domain)) return false; } public async checkAuthorizationToken(userID: string, token: string) { try { const resp = await axios({ url: 'https://comm.libraryofcode.org/internal/check-cwg-self-auth', params: { userID, token, internalKey: this.client.config.internalKey, }, }); if (resp?.status === 204) { return true; } return false; } catch { return false; } } /** * This function binds a domain to a port on the CWG. * @param account The account of the user. * @param subdomain The domain to use. `mydomain.cloud.libraryofcode.org` * @param port The port to use, must be between 1024 and 65535. * @param x509Certificate The contents the certificate and key files. * @example await CWG.createDomain(account, 'mydomain.cloud.libraryofcode.org', 6781); */ public async createDomain(account: AccountInterface, domain: string, port: number, x509Certificate: { cert?: string, key?: string }) { try { if (port <= 1024 || port >= 65535) throw new RangeError(`Port range must be between 1024 and 65535, received ${port}.`); if (await this.client.db.Domain.exists({ domain })) throw new Error(`Domain ${domain} already exists in the database.`); if (!await this.client.db.Account.exists({ userID: account.userID })) throw new Error(`Cannot find account ${account.userID}.`); let x509: { cert: string, key: string }; if (x509Certificate) { x509 = await this.createCertAndPrivateKey(domain, x509Certificate.cert, x509Certificate.key); } else { x509 = { cert: '/etc/ssl/private/cloud-libraryofcode-org.chain.crt', key: '/etc/ssl/private/cloud-libraryofcode-org.key', }; } let cfg = await fs.readFile('/opt/CloudServices/src/static/nginx.conf', { encoding: 'utf8' }); cfg = cfg.replace(/\[DOMAIN]/g, domain); cfg = cfg.replace(/\[PORT]/g, String(port)); cfg = cfg.replace(/\[CERTIFICATE]/g, x509.cert); cfg = cfg.replace(/\[KEY]/g, x509.key); await fs.writeFile(`/etc/nginx/sites-available/${domain}`, cfg, { encoding: 'utf8' }); await fs.symlink(`/etc/nginx/sites-available/${domain}`, `/etc/nginx/sites-enabled/${domain}`); const entry = new this.client.db.Domain({ account, domain, port, x509, enabled: true, }); return entry.save(); } catch (error) { const tasks = [fs.unlink(`/etc/nginx/sites-enabled/${domain}`), fs.unlink(`/etc/nginx/sites-available/${domain}`), this.client.db.Domain.deleteMany({ domain })]; await Promise.allSettled(tasks); throw error; } } public async createCertAndPrivateKey(domain: string, certChain: string, privateKey: string) { if (!this.isValidCertificateChain(certChain)) throw new Error('Invalid Certificate Chain'); // if (!this.isValidPrivateKey(privateKey)) throw new Error('Invalid Private Key'); const path = `/opt/CloudServices/temp/${domain}`; await Promise.all([writeFile(`${path}.chain.crt`, certChain), writeFile(`${path}.key.pem`, privateKey)]); if (!this.isMatchingPair(`${path}.chain.crt`, `${path}.key.pem`)) { await Promise.all([unlink(`${path}.chain.crt`), unlink(`${path}.key.pem`)]); throw new Error('Certificate and Private Key do not match'); } if (domain.endsWith('.cloud.libraryofcode.org')) { await Promise.all([symlink('/etc/ssl/private/cloud-libraryofcode-org.chain.crt', `/etc/ssl/certs/cwg/${domain}.chain.crt`), symlink('/etc/ssl/private/cloud-libraryofcode-org.key', `/etc/ssl/private/cwg/${domain}.key.pem`)]); } else { await Promise.all([writeFile(`/etc/ssl/certs/cwg/${domain}.chain.crt`, certChain), writeFile(`/etc/ssl/private/cwg/${domain}.key.pem`, privateKey)]); } return { cert: `/etc/ssl/certs/cwg/${domain}.chain.crt`, key: `/etc/ssl/private/cwg/${domain}.key.pem` }; } public checkOccurrence(text: string, query: string) { return (text.match(new RegExp(query, 'g')) || []).length; } public isValidCertificateChain(cert: string) { if (!cert.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN CERTIFICATE-----')) return false; if (!cert.replace(/^\s+|\s+$/g, '').endsWith('-----END CERTIFICATE-----')) return false; if (this.checkOccurrence(cert.replace(/^\s+|\s+$/g, ''), '-----BEGIN CERTIFICATE-----') !== 2) return false; if (this.checkOccurrence(cert.replace(/^\s+|\s+$/g, ''), '-----END CERTIFICATE-----') !== 2) return false; return true; } public isValidPrivateKey(key: string) { if (!key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN RSA PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN ECC PRIVATE KEY-----')) return false; if (!key.replace(/^\s+|\s+$/g, '').endsWith('-----END PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').endsWith('-----END RSA PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').endsWith('-----END ECC PRIVATE KEY-----')) return false; if ((this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN RSA PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN ECC PRIVATE KEY-----') !== 1)) return false; if ((this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END RSA PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END ECC PRIVATE KEY-----') !== 1)) return false; return true; } public async isMatchingPair(cert: string, privateKey: string) { const result: string = await this.client.util.exec(`${__dirname}/../bin/checkCertSignatures ${cert} ${privateKey}`); const { ok }: { ok: boolean } = JSON.parse(result); return ok; } }