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

Per-client SASL certificates #1463

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions changelog.d/1463.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Enable per-client SASL certificates
11 changes: 11 additions & 0 deletions config.sample.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,17 @@ ircService:
# real matrix users in them, even if there is a mapping for the channel.
# Default: true
joinChannelsIfNoUsers: true
#
# Explicit key/cert to use when connecting. Optional.
# When setting up with https://freenode.net/kb/answer/certfp , you can copy these from the .pem file
#sslKey: |
# -----BEGIN PRIVATE KEY-----
# ...
# -----END PRIVATE KEY-----
#saslCert: |
# -----BEGIN CERTIFICATE-----
# ...
# -----END CERTIFICATE-----

# Configuration for PMs / private 1:1 communications between users.
privateMessages:
Expand Down
4 changes: 4 additions & 0 deletions config.schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,10 @@ properties:
type: "string"
joinChannelsIfNoUsers:
type: "boolean"
saslKey:
type: "string"
saslCert:
type: "string"
privateMessages:
type: "object"
properties:
Expand Down
34 changes: 17 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "matrix-appservice-irc",
"version": "0.33.1",
"version": "0.34.0",
"description": "An IRC Bridge for Matrix",
"main": "app.js",
"bin": "./bin/matrix-appservice-irc",
"engines": {
"node": ">=14"
"node": ">=16"
},
"scripts": {
"prepare": "npm run build",
Expand Down Expand Up @@ -34,7 +34,7 @@
"he": "^1.2.0",
"logform": "^2.4.0",
"matrix-appservice-bridge": "^3.2.0",
"matrix-org-irc": "^1.2.0",
"matrix-org-irc": "^1.2.1",
"matrix-bot-sdk": "0.5.19",
"nopt": "^3.0.1",
"p-queue": "^6.6.2",
Expand All @@ -54,7 +54,7 @@
"@types/extend": "^3.0.1",
"@types/he": "^1.1.2",
"@types/nedb": "^1.8.12",
"@types/node": "^14",
"@types/node": "^16",
"@types/nopt": "^3.0.29",
"@types/pg": "^8.6.4",
"@types/sanitize-html": "^2.6.2",
Expand Down
164 changes: 163 additions & 1 deletion src/bridge/AdminRoomHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import * as crypto from "crypto";
import { BridgeRequest } from "../models/BridgeRequest";
import { MatrixRoom, MatrixUser } from "matrix-appservice-bridge";
import { IrcBridge } from "./IrcBridge";
Expand Down Expand Up @@ -91,6 +92,22 @@ const COMMANDS: {[command: string]: Command|Heading} = {
example: `!username [irc.example.net] username`,
summary: "Store a username to use for future connections.",
},
"!storecert": {
example: `!storecert irc.example.net] -----BEGIN CERTIFICATE-----[...]`,
summary: `Store a SASL certificate for CertFP`,
},
"!storekey": {
example: `!storekey [irc.example.net] -----BEGIN PRIVATE KEY-----[...]`,
summary: `Store a SASL private key for CertFP`,
},
"!removecert": {
example: `!removecert [irc.example.net]`,
summary: `Remove a previously stored SASL certificate`,
},
"!removekey": {
example: `!removekey [irc.example.net]`,
summary: `Remove a previously stored SASL private key`,
},
'Info': { heading: true},
"!bridgeversion": {
example: `!bridgeversion`,
Expand Down Expand Up @@ -176,6 +193,14 @@ export class AdminRoomHandler {
return await this.handleStorePass(req, args, event.sender);
case "!removepass":
return await this.handleRemovePass(args, event.sender);
case "!storekey":
return await this.handleStoreKey(req, args, event.sender);
case "!storecert":
return await this.handleStoreCert(req, args, event.sender);
case "!removekey":
return await this.handleRemoveKey(args, event.sender);
case "!removecert":
return await this.handleRemoveCert(args, event.sender);
case "!listrooms":
return await this.handleListRooms(args, event.sender);
case "!quit":
Expand Down Expand Up @@ -469,7 +494,7 @@ export class AdminRoomHandler {
let notice;

try {
// Allow passwords with spaces
// Allow usernames with spaces
const username = args[0]?.trim();
if (!username) {
notice = new MatrixAction(
Expand Down Expand Up @@ -563,6 +588,143 @@ export class AdminRoomHandler {
}
}

private async handleStoreKey(req: BridgeRequest, args: string[], userId: string) {
const server = this.extractServerFromArgs(args);
const domain = server.domain;
let notice;

try {
const key = args.join(' ').replace(/(-----([A-Z ]*)-----)\s*/g, '\n$1\n').trim().replace('\n\n', '\n');
if (key.length === 0) {
notice = new MatrixAction(
"notice",
"Format: '!storekey key' or '!storepass irc.server.name key'\n"
);
}
else {
try {
const pk = crypto.createPrivateKey(key);
const config = await this.ircBridge.getStore().getIrcClientConfig(userId, server.domain);
if (config) {
const cert = config.getSASLCert();
if (cert) {
const c = new crypto.X509Certificate(cert);
if (!c.checkPrivateKey(pk)) {
return new MatrixAction(
"notice",
"Private key does not match stored certificate. " +
"To store a new pair, first call !removecert.\n"
);
}
}
}
}
catch (err) {
throw new Error(`Invalid private key: ${err.message})`);
}
await this.ircBridge.getStore().storeKey(userId, domain, key);
notice = new MatrixAction(
"notice", `Successfully stored SASL key for ${domain}. Use !reconnect to reauthenticate.`
);
}
}
catch (err) {
req.log.error(err.stack);
return new MatrixAction(
"notice", `Failed to store SASL key: ${err.message}`
);
}
return notice;
}

private async handleRemoveKey(args: string[], userId: string) {
const server = this.extractServerFromArgs(args);

try {
await this.ircBridge.getStore().removeKey(userId, server.domain);
return new MatrixAction(
"notice", `Successfully removed SASL key.`
);
}
catch (err) {
return new MatrixAction(
"notice", `Failed to remove SASL key: ${err.message}`
);
}
}

private async handleStoreCert(req: BridgeRequest, args: string[], userId: string) {
const server = this.extractServerFromArgs(args);
const domain = server.domain;
let notice;

try {
const cert = args.join(' ').replace(/(-----([A-Z ]*)-----)\s*/g, '\n$1\n').trim().replace('\n\n', '\n');
if (cert.length === 0) {
notice = new MatrixAction(
"notice",
"Format: '!storecert cert' or '!storecert irc.server.name cert'\n"
);
}
else {
let config = await this.ircBridge.getStore().getIrcClientConfig(userId, server.domain);
if (!config) {
config = IrcClientConfig.newConfig(
new MatrixUser(userId), server.domain
);
}
let c: crypto.X509Certificate;
try {
c = new crypto.X509Certificate(cert);
const pk = config.getSASLKey();
if (pk) {
if (!c.checkPrivateKey(crypto.createPrivateKey(pk))) {
return new MatrixAction(
"notice",
"Certificate does not match stored private key. " +
"To store a new pair, first call !removekey.\n"
);
}
}
}
catch (err) {
throw new Error(`Invalid certificate: ${err.message})`);
}
const fingerprint512 = crypto.createHash('sha512').update(c.raw).digest('hex')
.replace(/:/g, '').toLowerCase();
config.setSASLCert(cert);
await this.ircBridge.getStore().storeIrcClientConfig(config);
notice = new MatrixAction(
"notice", `Successfully stored SASL cert for ${domain} with fingerprint ${fingerprint512}.\n' +
'Use !reconnect to reauthenticate.`
);
}
}
catch (err) {
req.log.error(err.stack);
return new MatrixAction(
"notice", `Failed to store SASL cert: ${err.message}`
);
}
return notice;
}

private async handleRemoveCert(args: string[], userId: string) {
const server = this.extractServerFromArgs(args);

try {
await this.ircBridge.getStore().removeCert(userId, server.domain);
return new MatrixAction(
"notice", `Successfully removed SASL cert.`
);
}
catch (err) {
return new MatrixAction(
"notice", `Failed to remove SASL cert: ${err.message}`
);
}
}

private async handleListRooms(args: string[], sender: string) {
const server = this.extractServerFromArgs(args);

Expand Down
2 changes: 1 addition & 1 deletion src/bridge/RoomConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class RoomConfig {
// We don't want to spend too long trying to fetch the state, so return null.
return Promise.race([
internalFunc(),
new Promise<null>(res => setTimeout(res, STATE_TIMEOUT_MS)),
new Promise<null>(res => setTimeout(res as unknown as ((args: void) => void), STATE_TIMEOUT_MS)),
// We *never* want this function to throw, as it's critical for the bridging of messages.
// Instead we return null for any errors.
]).catch(ex => {
Expand Down
8 changes: 8 additions & 0 deletions src/datastore/DataStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ export interface DataStore {

removePass(userId: string, domain: string): Promise<void>;

storeKey(userId: string, domain: string, key: string): Promise<void>;

removeKey(userId: string, domain: string): Promise<void>;

storeCert(userId: string, domain: string, cert: string): Promise<void>;

removeCert(userId: string, domain: string): Promise<void>;

getMatrixUserByUsername(domain: string, username: string): Promise<MatrixUser|undefined>;

getCountForUsernamePrefix(domain: string, usernamePrefix: string): Promise<number>;
Expand Down
Loading