diff --git a/src/class/Util.ts b/src/class/Util.ts index 2d3cf4b..5fe2862 100644 --- a/src/class/Util.ts +++ b/src/class/Util.ts @@ -169,7 +169,7 @@ export default class Util { await this.exec(`chage -d0 ${username}`); const account = await new this.client.db.Account({ - username, userID, emailAddress, createdBy: moderatorID, createdAt: new Date(), locked: false, + username, userID, emailAddress, createdBy: moderatorID, createdAt: new Date(), locked: false, ssInit: false, }); return account.save(); } diff --git a/src/commands/cwg.ts b/src/commands/cwg.ts index be3e69b..502f51f 100644 --- a/src/commands/cwg.ts +++ b/src/commands/cwg.ts @@ -1,11 +1,5 @@ -/* -import fs from 'fs-extra'; -import axios from 'axios'; -import moment from 'moment'; -import x509 from '@ghaiklor/x509'; -*/ import { Message } from 'eris'; -import { Command/* , RichEmbed */ } from '../class'; +import { Command } from '../class'; import { Client } from '..'; import Create from './cwg_create'; import Data from './cwg_data'; @@ -25,183 +19,8 @@ export default class CWG extends Command { public async run(message: Message) { try { return this.client.commands.get('help').run(message, [this.name]); - /* - args[1] should be the user's ID OR account username; required - args[2] should be the domain; required - args[3] should be the port; required - args[4] should be the path to the x509 certificate; not required - args[5] should be the path to the x509 key; not required - */ /* - if (args[0] === 'create') { - if (!args[3]) return this.client.commands.get('help').run(message, [this.name]); - try { - if (!message.member.roles.includes('525441307037007902')) return; // eslint-disable-line - const edit = await message.channel.createMessage(`***${this.client.stores.emojis.loading} Binding domain...***`); - const account = await this.client.db.Account.findOne({ $or: [{ username: args[1] }, { userID: args[1] }] }); - if (!account) return edit.edit(`${this.client.stores.emojis.error} Cannot locate account, please try again.`); - if (args[4] && !args[5]) return edit.edit(`${this.client.stores.emojis.error} x509 Certificate key required`); - let certs: { cert?: string, key?: string }; if (args[5]) certs = { cert: args[4], key: args[5] }; - if (await this.client.db.Domain.exists({ domain: args[2] })) return edit.edit(`***${this.client.stores.emojis.error} This domain already exists.***`); - if (await this.client.db.Domain.exists({ port: Number(args[3]) })) return edit.edit(`***${this.client.stores.emojis.error} This port is already binded to a domain.***`); - const domain = await this.createDomain(account, args[2], Number(args[3]), certs); - const embed = new RichEmbed(); - embed.setTitle('Domain Creation'); - embed.setColor(3066993); - embed.addField('Account Username', account.username, true); - embed.addField('Account ID', account.id, true); - embed.addField('Engineer', `<@${message.author.id}>`, true); - embed.addField('Domain', domain.domain, true); - embed.addField('Port', String(domain.port), true); - const cert = x509.parseCert(await fs.readFile(domain.x509.cert, { encoding: 'utf8' })); - embed.addField('Certificate Issuer', cert.issuer.organizationName, true); - embed.addField('Certificate Subject', cert.subject.commonName, true); - embed.setFooter(this.client.user.username, this.client.user.avatarURL); - embed.setTimestamp(new Date(message.timestamp)); - message.delete(); - await this.client.util.exec('systemctl reload nginx'); - edit.edit(`***${this.client.stores.emojis.success} Successfully binded ${domain.domain} to port ${domain.port} for ${account.userID}.***`); - // @ts-ignore - this.client.createMessage('580950455581147146', { embed }); - // @ts-ignore - this.client.getDMChannel(account.userID).then((r) => r.createMessage({ embed })); - await this.client.util.transport.sendMail({ - to: account.emailAddress, - from: 'Library of Code sp-us | Support Team ', - subject: 'Your domain has been binded', - html: ` -

Library of Code sp-us | Cloud Services

-

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

- Domain: ${domain.domain} - Port: ${domain.port} - Certificate Issuer: ${cert.issuer.organizationName} - Certificate Subject: ${cert.subject.commonName} - Responsible Engineer: ${message.author.username}#${message.author.discriminator} - - 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 - `, - }); - if (!domain.domain.includes('cloud.libraryofcode.org')) { - const content = `__**DNS Record Setup**__\nYou recently a binded a custom domain to your Library of Code sp-us Account. You'll have to update your DNS records. We've provided the records below.\n\n\`${domain.domain} IN CNAME cloud.libraryofcode.org AUTO/500\`\nThis basically means you need to make a CNAME record with the key/host of ${domain.domain} and the value/point to cloud.libraryofcode.org. If you have any questions, don't hesitate to ask us.`; - this.client.getDMChannel(account.userID).then((r) => r.createMessage(content)); - } - } catch (err) { - this.client.util.handleError(err, message, this); - await fs.unlink(`/etc/nginx/sites-available/${args[2]}`); - await fs.unlink(`/etc/nginx/sites-enabled/${args[2]}`); - await this.client.db.Domain.deleteMany({ domain: args[2] }); - } - } else if (args[0] === 'data') { - if (!args[1]) return this.client.commands.get('help').run(message, [this.name]); - const domain = await this.client.db.Domain.findOne({ $or: [{ domain: args[1] }, { port: Number(args[1]) || '' }] }); - if (!domain) return message.channel.createMessage(`***${this.client.stores.emojis.error} The domain or port you provided could not be found.***`); - const embed = new RichEmbed(); - embed.setTitle('Domain Information'); - embed.addField('Account Username', domain.account.username, true); - embed.addField('Account ID', domain.account.userID, true); - embed.addField('Domain', domain.domain, true); - embed.addField('Port', String(domain.port), true); - embed.addField('Certificate Issuer', x509.getIssuer(await fs.readFile(domain.x509.cert, { encoding: 'utf8' })).organizationName, true); - embed.addField('Certificate Subject', x509.getSubject(await fs.readFile(domain.x509.cert, { encoding: 'utf8' })).commonName, true); - embed.addField('Certificate Expiration Date', moment(x509.parseCert(await fs.readFile(domain.x509.cert, { encoding: 'utf8' })).notAfter).format('dddd, MMMM Do YYYY, h:mm:ss A'), true); - embed.setFooter(this.client.user.username, this.client.user.avatarURL); - embed.setTimestamp(); - // @ts-ignore - message.channel.createMessage({ embed }); - } else if (args[0] === 'delete') { - if (!args[1]) return this.client.commands.get('help').run(message, [this.name]); - const domain = await this.client.db.Domain.findOne({ $or: [{ domain: args[1] }, { port: Number(args[1]) || '' }] }); - if (!domain) return message.channel.createMessage(`***${this.client.stores.emojis.error} The domain or port you provided could not be found.***`); - const edit = await message.channel.createMessage(`***${this.client.stores.emojis.loading} Deleting domain...***`); - const embed = new RichEmbed(); - embed.setTitle('Domain Deletion'); - embed.addField('Account Username', domain.account.username, true); - embed.addField('Account ID', domain.account.userID, true); - embed.addField('Domain', domain.domain, true); - embed.addField('Port', String(domain.port), true); - embed.setFooter(this.client.user.username, this.client.user.avatarURL); - embed.setTimestamp(); - if (domain.domain.includes('cloud.libraryofcode.org')) { - const resultID = await axios({ - method: 'get', - url: `https://api.cloudflare.com/client/v4/zones/5e82fc3111ed4fbf9f58caa34f7553a7/dns_records?name=${domain.domain}`, - headers: { Authorization: `Bearer ${this.client.config.cloudflare}` }, - }); - this.client.signale.debug(resultID.data); - if (resultID.data.result[0]) { - const recordID = resultID.data.result[0].id; - await axios({ - method: 'delete', - url: `https://api.cloudflare.com/client/v4/zones/5e82fc3111ed4fbf9f58caa34f7553a7/dns_records/${recordID}`, - headers: { Authorization: `Bearer ${this.client.config.cloudflare}` }, - }); - } - } - try { - await fs.unlink(`/etc/nginx/sites-enabled/${domain.domain}`); - await fs.unlink(`/etc/nginx/sites-available/${domain.domain}`); - } catch (e) { this.client.signale.error(e); } - await this.client.db.Domain.deleteOne({ domain: domain.domain }); - await this.client.util.exec('systemctl reload nginx'); - edit.edit(`***${this.client.stores.emojis.success} Domain ${domain.domain} with port ${domain.port} has been successfully deleted.***`); - // @ts-ignore - message.channel.createMessage({ embed }); - } else { message.channel.createMessage(`${this.client.stores.emojis.error} Not a valid subcommand.`); } - return true; - */ } catch (error) { return this.client.util.handleError(error, message, this); } } - - /** - * 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 x509 The paths to the certificate and key files. Must be already existant. - * @example await CWG.createDomain('mydomain.cloud.libraryofcode.org', 6781); - */ /* - public async createDomain(account: AccountInterface, domain: string, port: number, x509Certificate: { cert?: string, key?: string } = { cert: '/etc/nginx/ssl/cloud-org.chain.crt', key: '/etc/nginx/ssl/cloud-org.key.pem' }) { - 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({ port })) throw new Error(`Port ${port} already exists in the database.`); - 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}.`); - await fs.access(x509Certificate.cert, fs.constants.R_OK); - await fs.access(x509Certificate.key, fs.constants.R_OK); - let cfg = await fs.readFile('/var/CloudServices/dist/static/nginx.conf', { encoding: 'utf8' }); - cfg = cfg.replace(/\[DOMAIN]/g, domain); - cfg = cfg.replace(/\[PORT]/g, String(port)); - cfg = cfg.replace(/\[CERTIFICATE]/g, x509Certificate.cert); - cfg = cfg.replace(/\[KEY]/g, x509Certificate.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: x509Certificate, - enabled: true, - }); - if (domain.includes('cloud.libraryofcode.org')) { - const dmn = domain.split('.'); - await axios({ - method: 'post', - url: 'https://api.cloudflare.com/client/v4/zones/5e82fc3111ed4fbf9f58caa34f7553a7/dns_records', - headers: { Authorization: `Bearer ${this.client.config.cloudflare}`, 'Content-Type': 'application/json' }, - data: JSON.stringify({ type: 'CNAME', name: `${dmn[0]}.${dmn[1]}`, content: 'cloud.libraryofcode.org', proxied: false }), - }); - } - return entry.save(); - } catch (error) { - await fs.unlink(`/etc/nginx/sites-enabled/${domain}`); - await fs.unlink(`/etc/nginx/sites-available/${domain}`); - await this.client.db.Domain.deleteMany({ domain }); - throw error; - } - } - */ } diff --git a/src/commands/eval.ts b/src/commands/eval.ts index 5e4f6f1..16d9fc3 100644 --- a/src/commands/eval.ts +++ b/src/commands/eval.ts @@ -13,6 +13,7 @@ export default class Eval extends Command { this.description = 'Evaluate JavaScript code'; this.enabled = true; this.permissions = { users: ['253600545972027394', '278620217221971968'] }; + this.guildOnly = false; } public async run(message: Message, args: string[]) { diff --git a/src/commands/exec.ts b/src/commands/exec.ts index 17ae8ca..164efcf 100644 --- a/src/commands/exec.ts +++ b/src/commands/exec.ts @@ -11,6 +11,7 @@ export default class Exec extends Command { this.aliases = ['ex']; this.enabled = true; this.permissions = { users: ['253600545972027394', '278620217221971968'] }; + this.guildOnly = false; } public async run(message: Message, args: string[]) { diff --git a/src/commands/index.ts b/src/commands/index.ts index f0fb9b3..ef40be2 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -13,6 +13,7 @@ export { default as Parse } from './parse'; export { default as Parseall } from './parseall'; export { default as Ping } from './ping'; export { default as Pull } from './pull'; +export { default as SecureSign } from './securesign'; export { default as Sysinfo } from './sysinfo'; export { default as Unlock } from './unlock'; export { default as Warn } from './warn'; diff --git a/src/commands/securesign.ts b/src/commands/securesign.ts new file mode 100644 index 0000000..df4ae28 --- /dev/null +++ b/src/commands/securesign.ts @@ -0,0 +1,25 @@ +import { Message } from 'eris'; +import { Command } from '../class'; +import { Client } from '..'; +import Build from './securesign_build'; +import Init from './securesign_init'; + +export default class SecureSign extends Command { + constructor(client: Client) { + super(client); + this.name = 'securesign'; + this.description = 'Runs SecureSign CLI commands'; + this.usage = `Run ${this.client.config.prefix}${this.name} [subcommand] for usage information`; + this.aliases = ['ss']; + this.subcmds = [Build, Init]; + this.enabled = true; + } + + public async run(message: Message) { + try { + return this.client.commands.get('help').run(message, [this.name]); + } catch (error) { + return this.client.util.handleError(error, message, this); + } + } +} diff --git a/src/commands/securesign_build.ts b/src/commands/securesign_build.ts new file mode 100644 index 0000000..fb28b3e --- /dev/null +++ b/src/commands/securesign_build.ts @@ -0,0 +1,36 @@ +import { Message } from 'eris'; +import { Client } from '..'; +import { Command, RichEmbed } from '../class'; + +export default class SecureSign_Build extends Command { + constructor(client: Client) { + super(client); + this.name = 'build'; + this.description = 'Shows information about the current build of the CLI'; + this.usage = `${this.client.config.prefix}securesign build`; + this.enabled = true; + } + + public async run(message: Message, args: string[]) { + try { + const msg = await message.channel.createMessage(`${this.client.stores.emojis.loading} ***Loading build information...***`); + + const build = await this.client.util.exec("sudo -H -u root bash -c 'securesign-canary build'"); + const info = build.replace(/^\s+|\s+$/g, '').replace(/\n/g, '\n**').replace(/: /g, ':** ').split('\n'); + const title = info.shift(); + const description = info.join('\n'); + const content = ''; + + const embed = new RichEmbed(); + embed.setTitle(title); + embed.setDescription(description); + embed.setAuthor(this.client.user.username, this.client.user.avatarURL); + embed.setFooter(`Requested by ${message.member.username}#${message.member.discriminator}`, message.member.avatarURL); + + // @ts-ignore + msg.edit({ content, embed }); + } catch (error) { + this.client.util.handleError(error, message, this); + } + } +} diff --git a/src/commands/securesign_init.ts b/src/commands/securesign_init.ts new file mode 100644 index 0000000..0ec9ab1 --- /dev/null +++ b/src/commands/securesign_init.ts @@ -0,0 +1,55 @@ +import { Message, PrivateChannel, TextChannel } from 'eris'; +import axios, { AxiosResponse } from 'axios'; +import { Client } from '..'; +import { Command } from '../class'; + +export default class SecureSign_Init extends Command { + constructor(client: Client) { + super(client); + this.name = 'init'; + this.description = 'Inits configuration files and environment variables (DM only)'; + this.usage = `${this.client.config.prefix}securesign init [hash]`; + this.enabled = true; + this.guildOnly = false; + } + + public async run(message: Message, args: string[]) { + try { + if (!args[0]) return this.client.commands.get('help').run(message, ['securesign', this.name]); + if (!(message.channel instanceof PrivateChannel)) { + message.delete(); + return message.channel.createMessage(`${this.client.stores.emojis.error} ***Run this command in your DMs!***`); + } + const account = await this.client.db.Account.findOne({ userID: message.author.id }); + if (!account) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Account not registered***`); + if (account.locked) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Your account is locked***`); + const msg = await message.channel.createMessage(`${this.client.stores.emojis.loading} ***Initializing account...***`); + let verify: AxiosResponse; + try { + verify = await axios({ + method: 'get', + url: 'https://api.securesign.org/account/details', + headers: { Authorization: args[0] }, + }); + } catch (error) { + const { status } = error.response; + if (status === 400 || status === 401 || status === 403 || status === 404) return msg.edit(`${this.client.stores.emojis.error} ***Credentials incorrect***`); + throw error; + } + const { id } = verify.data.message; + if (id !== message.author.id && !account.root) { + // @ts-ignore + const channel: TextChannel = this.client.guilds.get('446067825673633794').channels.get('501089664040697858'); + channel.createMessage(`**__UNAUTHORIZED ACCESS ALERT__**\n${message.author.mention} tried to initialize their account using <@${id}>'s SecureSign credentials.\nTheir account has been locked under Section 5.2 of the EULA.`); + const tasks = [this.client.util.exec(`lock ${account.username}`), account.updateOne({ locked: true }), this.client.util.createModerationLog(account.userID, this.client.user, 2, 'Violation of Section 5.2 of the EULA')]; + await Promise.all(tasks); + return msg.edit(`${this.client.stores.emojis.error} ***Credentials incorrect***`); + } + const init = await this.client.util.exec(`sudo -H -u ${account.username} bash -c 'securesign-canary init -a ${args[0]}'`); + if (!init.replace(/^\s+|\s+$/g, '').endsWith('Initialization sequence completed.')) throw new Error(`Account initialization did not complete successfully:\n${init}`); + return msg.edit(`${this.client.stores.emojis.success} ***Account initialized***`); + } catch (error) { + return this.client.util.handleError(error, message, this); + } + } +} diff --git a/src/models/Account.ts b/src/models/Account.ts index b84f492..16a5f51 100644 --- a/src/models/Account.ts +++ b/src/models/Account.ts @@ -16,6 +16,7 @@ export interface AccountInterface extends Document { engineer: boolean }, root: boolean + ssInit: boolean } const Account: Schema = new Schema({ @@ -34,6 +35,7 @@ const Account: Schema = new Schema({ engineer: Boolean, }, root: Boolean, + ssInit: Boolean, }); export default model('Account', Account);