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

Auth plugin caching sha2 password #68

Merged
Merged
Show file tree
Hide file tree
Changes from 14 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
Binary file added cipher
Binary file not shown.
10 changes: 2 additions & 8 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { encode, Hash, sha256 } from "../deps.ts";

function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
return a.map((byte, index) => {
return byte ^ b[index];
});
}
import { xor } from "./util.ts";

function mysqlNativePassword(password: string, seed: Uint8Array): Uint8Array {
const hash = new Hash("sha1");
Expand Down Expand Up @@ -36,8 +31,7 @@ export default function auth(
return mysqlNativePassword(password, seed);

case "caching_sha2_password":
// TODO
// return cachingSha2Password(password, seed);
return cachingSha2Password(password, seed);
default:
throw new Error("Not supported");
}
Expand Down
69 changes: 69 additions & 0 deletions src/auth_plugin/caching_sha2_password.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { xor } from "../util.ts";
import { ReceivePacket } from "../packets/packet.ts";
import { encryptWithPublicKey } from "./crypt.ts";

interface handler {
done: boolean;
quickRead?: boolean;
next?: (packet: ReceivePacket) => any;
data?: Uint8Array;
}

let scramble: Uint8Array, password: string;
function start(scramble_: Uint8Array, password_: string): handler {
scramble = scramble_;
password = password_;
return { done: false, next: authMoreResponse };
}
function authMoreResponse(packet: ReceivePacket): handler {
const enum AuthStatusFlags {
FullAuth = 0x04,
FastPath = 0x03,
}
const REQUEST_PUBLIC_KEY = 0x02;
const statusFlag = packet.body.skip(1).readUint8();
let authMoreData, done = true, next, quickRead = false;
if (statusFlag === AuthStatusFlags.FullAuth) {
authMoreData = new Uint8Array([REQUEST_PUBLIC_KEY]);
done = false;
next = encryptWithKey;
}
if (statusFlag === AuthStatusFlags.FastPath) {
done = false;
quickRead = true;
next = terminate;
}
return { done, next, quickRead, data: authMoreData };
}

function encryptWithKey(packet: ReceivePacket): handler {
const publicKey = parsePublicKey(packet);
const len = password.length;
let passwordBuffer: Uint8Array = new Uint8Array(len + 1);
for (let n = 0; n < len; n++) {
passwordBuffer[n] = password.charCodeAt(n);
}
passwordBuffer[len] = 0x00;

const encryptedPassword = encrypt(passwordBuffer, scramble, publicKey);
return { done: false, next: terminate, data: encryptedPassword };
}

function parsePublicKey(packet: ReceivePacket): string {
return packet.body.skip(1).readNullTerminatedString();
}
function encrypt(
password: Uint8Array,
scramble: Uint8Array,
key: string,
): Uint8Array {
const stage1 = xor(password, scramble);
const encrypted = encryptWithPublicKey(key, stage1);
return encrypted;
}

function terminate() {
return { done: true };
}

export { start };
15 changes: 15 additions & 0 deletions src/auth_plugin/crypt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import "../lib/forge.js";
const forge = (self as any).forge;
const { publicKeyFromPem } = forge.pki;
function encryptWithPublicKey(key: string, data: Uint8Array): Uint8Array {
const publicKey = publicKeyFromPem(key);
const result = Array.prototype.map.call(data, (i) => String.fromCharCode(i))
.join("");
const cipher = publicKey.encrypt(result, "RSA-OAEP");
const encryptedData: Uint8Array = cipher.split("").map((item: string) =>
item.charCodeAt(0)
);
return encryptedData;
}

export { encryptWithPublicKey };
4 changes: 4 additions & 0 deletions src/auth_plugin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as caching_sha2_password from "./caching_sha2_password.ts";
export default {
caching_sha2_password,
};
60 changes: 52 additions & 8 deletions src/connection.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { delay } from "../deps.ts";
import { delay, byteFormat } from "../deps.ts";
import { Client } from "./client.ts";
import { ResponseTimeoutError } from "./constant/errors.ts";
import { log } from "./logger.ts";
import { buildAuth } from "./packets/builders/auth.ts";
import { buildQuery } from "./packets/builders/query.ts";
import { ReceivePacket, SendPacket } from "./packets/packet.ts";
import { parseError } from "./packets/parsers/err.ts";
import { parseHandshake } from "./packets/parsers/handshake.ts";
import {
parseHandshake,
parseAuth,
AuthResult,
} from "./packets/parsers/handshake.ts";
import { FieldInfo, parseField, parseRow } from "./packets/parsers/result.ts";
import { PacketType } from "./constant/packet.ts";
import authPlugin from "./auth_plugin/index.ts";

/**
* Connection state
Expand Down Expand Up @@ -40,7 +46,7 @@ export class Connection {
constructor(readonly client: Client) {}

private async _connect() {
const { hostname, port = 3306 } = this.client.config;
const { hostname, port = 3306, username, password } = this.client.config;
wenjoy marked this conversation as resolved.
Show resolved Hide resolved
log.info(`connecting ${hostname}:${port}`);
this.conn = await Deno.connect({
hostname,
Expand All @@ -51,16 +57,51 @@ export class Connection {
let receive = await this.nextPacket();
const handshakePacket = parseHandshake(receive.body);
const data = buildAuth(handshakePacket, {
username: this.client.config.username ?? "",
password: this.client.config.password,
username: username ?? "",
password,
db: this.client.config.db,
});

await new SendPacket(data, 0x1).send(this.conn);

this.state = ConnectionState.CONNECTING;
this.serverVersion = handshakePacket.serverVersion;
this.capabilities = handshakePacket.serverCapabilities;

receive = await this.nextPacket();

const authResult = parseAuth(receive);
let handler;

switch (authResult) {
case AuthResult.AuthMoreRequired:
const adaptedPlugin =
(authPlugin as any)[handshakePacket.authPluginName];
handler = adaptedPlugin;
break;
case AuthResult.MethodMismatch:
// TODO: Negotiate
throw new Error("Currently cannot support auth method mismatch!");
}

let result;
if (handler) {
result = handler.start(handshakePacket.seed, password!);
while (!result.done) {
if (result.data) {
const sequenceNumber = receive.header.no + 1;
await new SendPacket(result.data, sequenceNumber).send(this.conn);
receive = await this.nextPacket();
}
if (result.quickRead) {
await this.nextPacket();
}
if (result.next) {
result = result.next(receive);
}
}
}

const header = receive.body.readUint8();
if (header === 0xff) {
const error = parseError(receive.body, this);
Expand Down Expand Up @@ -88,8 +129,9 @@ export class Connection {

while (this.conn!) {
const packet = await new ReceivePacket().parse(this.conn!);

if (packet) {
if (packet.type === "ERR") {
if (packet.type === PacketType.ERR_Packet) {
packet.body.skip(1);
const error = parseError(packet.body, this);
throw new Error(error.message);
Expand Down Expand Up @@ -158,9 +200,11 @@ export class Connection {
throw new Error("Must be connected first");
}
const data = buildQuery(sql, params);

await new SendPacket(data, 0).send(this.conn);

let receive = await this.nextPacket();
if (receive.type === "OK") {
if (receive.type === PacketType.OK_Packet) {
receive.body.skip(1);
return {
affectedRows: receive.body.readEncodedLen(),
Expand All @@ -185,7 +229,7 @@ export class Connection {

while (true) {
receive = await this.nextPacket();
if (receive.type === "EOF") {
if (receive.type === PacketType.EOF_Packet) {
break;
} else {
const row = parseRow(receive.body, fields);
Expand Down
4 changes: 4 additions & 0 deletions src/constant/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ enum ServerCapabilities {
CLIENT_SECURE_CONNECTION = 0x8000,
CLIENT_FOUND_ROWS = 0x00000002,
CLIENT_CONNECT_ATTRS = 0x00100000,
CLIENT_IGNORE_SPACE = 0x00000100,
CLIENT_IGNORE_SIGPIPE = 0x00001000,
CLIENT_RESERVED = 0x00004000,
CLIENT_PS_MULTI_RESULTS = 0x00040000,
}

export default ServerCapabilities;
6 changes: 6 additions & 0 deletions src/constant/packet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export enum PacketType {
OK_Packet = 0x00,
EOF_Packet = 0xfe,
ERR_Packet = 0xff,
Result,
}
Loading