Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
5278c2ce78 | |||
439d08b023 | |||
1536475306 | |||
5c06ae1edb |
102
changelog.md
Normal file
102
changelog.md
Normal file
@ -0,0 +1,102 @@
|
||||
# Changelog
|
||||
|
||||
## 2024-09-19 - 6.1.1 - fix(ts_server)
|
||||
Update DnsSec class to fully implement key generation and DNSKEY record creation.
|
||||
|
||||
- Added complete support for ECDSA and ED25519 algorithms in the DnsSec class.
|
||||
- Implemented DNSKEY generation and KeyTag computation methods.
|
||||
- Improved error handling and initialized the appropriate cryptographic instances based on the algorithm.
|
||||
|
||||
## 2024-09-18 - 6.1.0 - feat(smartdns)
|
||||
Add DNS Server and DNSSEC tools with comprehensive unit tests
|
||||
|
||||
- Updated package dependencies to the latest versions
|
||||
- Introduced DnsServer class for handling DNS requests over both HTTPS and UDP with support for custom handlers
|
||||
- Added DnsSec class for generating and managing DNSSEC keys and DS records
|
||||
- Implemented unit tests for DnsServer and Smartdns classes
|
||||
|
||||
## 2024-06-02 - 6.0.0 - server/client
|
||||
Main description here
|
||||
|
||||
- **Breaking Change:** Move from client only to server + client exports.
|
||||
|
||||
## 2024-03-30 - 5.0.4 - maintenance
|
||||
Range contains relevant changes
|
||||
|
||||
- Switch to new org scheme
|
||||
|
||||
## 2023-04-08 - 5.0.4 - core
|
||||
Main description here
|
||||
|
||||
- Core update
|
||||
- Fixes applied to the system
|
||||
|
||||
## 2022-07-27 - 5.0.0 - core
|
||||
Update contains relevant changes
|
||||
|
||||
- **Breaking Change:** Major update and core changes
|
||||
- Fixes and updates applied
|
||||
|
||||
## 2022-07-27 - 4.0.11 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- **Breaking Change:** Core update and changes applied
|
||||
|
||||
## 2021-08-24 - 4.0.10 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- Fixes applied to the core functionalities
|
||||
|
||||
## 2021-01-23 - 4.0.8 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- Updates and fixes to the core components
|
||||
|
||||
## 2020-08-05 - 4.0.4 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- Multiple core fixes applied
|
||||
|
||||
## 2020-02-15 - 4.0.0 - core
|
||||
Main description here
|
||||
|
||||
- Core updates
|
||||
- Fixes applied across the system
|
||||
|
||||
## 2020-02-15 - 3.0.8 - core
|
||||
Core updates with major changes
|
||||
|
||||
- **Breaking Change:** Now uses Google DNS HTTPS API and handles DNSSEC validation
|
||||
|
||||
## 2019-01-07 - 3.0.6 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- Fixes and updates applied to the core
|
||||
|
||||
## 2018-05-13 - 3.0.4 - core
|
||||
Range contains relevant changes
|
||||
|
||||
- Fixes applied, including `fix .checkUntilAvailable` error
|
||||
|
||||
## 2018-05-13 - 3.0.0 - ci
|
||||
Main description here
|
||||
|
||||
- CI changes and updates to the access level and global packages
|
||||
|
||||
## 2017-07-31 - 2.0.10 - package
|
||||
Update to new package name and improved record retrieval
|
||||
|
||||
- **Breaking Change:** Package name update and record retrieval improvements
|
||||
|
||||
## 2017-01-27 - 2.0.1 - maintenance
|
||||
Multiple fixes and merges
|
||||
|
||||
## 2017-01-27 - 2.0.0 - core
|
||||
Fix typings and update to better API
|
||||
|
||||
## 2016-11-15 - 1.0.7 - initial
|
||||
Initial setup and improvements
|
||||
|
||||
- Initial deployment
|
||||
- README improvements
|
||||
|
19
package.json
19
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartdns",
|
||||
"version": "6.0.0",
|
||||
"version": "6.1.1",
|
||||
"private": false,
|
||||
"description": "A TypeScript library for smart DNS methods, supporting various DNS records and providers.",
|
||||
"exports": {
|
||||
@ -36,18 +36,21 @@
|
||||
"dependencies": {
|
||||
"@push.rocks/smartdelay": "^3.0.1",
|
||||
"@push.rocks/smartenv": "^5.0.5",
|
||||
"@push.rocks/smartpromise": "^4.0.2",
|
||||
"@push.rocks/smartpromise": "^4.0.4",
|
||||
"@push.rocks/smartrequest": "^2.0.15",
|
||||
"@tsclass/tsclass": "^4.0.54",
|
||||
"@tsclass/tsclass": "^4.1.2",
|
||||
"@types/dns-packet": "^5.6.5",
|
||||
"dns-packet": "^5.6.1"
|
||||
"@types/elliptic": "^6.4.18",
|
||||
"dns-packet": "^5.6.1",
|
||||
"elliptic": "^6.5.7",
|
||||
"minimatch": "^10.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tsbuild": "^2.1.84",
|
||||
"@git.zone/tsrun": "^1.2.49",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.0.8",
|
||||
"@types/node": "^20.13.0"
|
||||
"@push.rocks/tapbundle": "^5.2.0",
|
||||
"@types/node": "^22.5.5"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
|
878
pnpm-lock.yaml
generated
878
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,163 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import { tapNodeTools } from '@push.rocks/tapbundle/node';
|
||||
|
||||
import * as dnsPacket from 'dns-packet';
|
||||
import * as https from 'https';
|
||||
import * as dgram from 'dgram';
|
||||
|
||||
import * as smartdns from '../ts_server/index.js';
|
||||
|
||||
let dnsServer: smartdns.DnsServer;
|
||||
|
||||
tap.test('should create an instance of DnsServer', async () => {
|
||||
// Use valid options
|
||||
const httpsData = await tapNodeTools.createHttpsCert();
|
||||
dnsServer = new smartdns.DnsServer({
|
||||
httpsKey: httpsData.key,
|
||||
httpsCert: httpsData.cert,
|
||||
httpsPort: 8080,
|
||||
udpPort: 8081,
|
||||
});
|
||||
expect(dnsServer).toBeInstanceOf(smartdns.DnsServer);
|
||||
});
|
||||
|
||||
tap.test('should start the server', async () => {
|
||||
await dnsServer.start();
|
||||
// @ts-ignore
|
||||
expect(dnsServer.httpsServer).toBeDefined();
|
||||
});
|
||||
|
||||
tap.test('lets add a handler', async () => {
|
||||
dnsServer.registerHandler('*.bleu.de', ['A'], (question) => {
|
||||
return {
|
||||
name: question.name,
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
data: '127.0.0.1',
|
||||
};
|
||||
});
|
||||
|
||||
// @ts-ignore
|
||||
const response = dnsServer.processDnsRequest({
|
||||
type: 'query',
|
||||
id: 1,
|
||||
flags: 0,
|
||||
questions: [
|
||||
{
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
},
|
||||
],
|
||||
answers: [],
|
||||
});
|
||||
expect(response.answers[0]).toEqual({
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
data: '127.0.0.1',
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('lets query over https', async () => {
|
||||
const query = dnsPacket.encode({
|
||||
type: 'query',
|
||||
id: 2,
|
||||
flags: dnsPacket.RECURSION_DESIRED,
|
||||
questions: [
|
||||
{
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await fetch('https://localhost:8080/dns-query', {
|
||||
method: 'POST',
|
||||
body: query,
|
||||
headers: {
|
||||
'Content-Type': 'application/dns-message',
|
||||
}
|
||||
});
|
||||
|
||||
expect(response.status).toEqual(200);
|
||||
|
||||
const responseData = await response.arrayBuffer();
|
||||
const dnsResponse = dnsPacket.decode(Buffer.from(responseData));
|
||||
|
||||
console.log(dnsResponse.answers[0]);
|
||||
|
||||
expect(dnsResponse.answers[0]).toEqual({
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
flush: false,
|
||||
data: '127.0.0.1',
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('lets query over udp', async () => {
|
||||
const client = dgram.createSocket('udp4');
|
||||
|
||||
const query = dnsPacket.encode({
|
||||
type: 'query',
|
||||
id: 3,
|
||||
flags: dnsPacket.RECURSION_DESIRED,
|
||||
questions: [
|
||||
{
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const responsePromise = new Promise<dnsPacket.Packet>((resolve, reject) => {
|
||||
client.on('message', (msg) => {
|
||||
const dnsResponse = dnsPacket.decode(msg);
|
||||
resolve(dnsResponse);
|
||||
client.close();
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
reject(err);
|
||||
client.close();
|
||||
});
|
||||
|
||||
client.send(query, 8081, 'localhost', (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const dnsResponse = await responsePromise;
|
||||
|
||||
console.log(dnsResponse.answers[0]);
|
||||
|
||||
expect(dnsResponse.answers[0]).toEqual({
|
||||
name: 'dnsly_a.bleu.de',
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
flush: false,
|
||||
data: '127.0.0.1',
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should run for a while', async (toolsArg) => {
|
||||
await toolsArg.delayFor(1000);
|
||||
});
|
||||
|
||||
tap.test('should stop the server', async () => {
|
||||
await dnsServer.stop();
|
||||
// @ts-ignore
|
||||
expect(dnsServer.httpsServer).toBeFalsy();
|
||||
});
|
||||
|
||||
await tap.start();
|
@ -24,7 +24,7 @@ export const makeNodeProcessUseDnsProvider = (providerArg: TDnsProvider) => {
|
||||
|
||||
export interface ISmartDnsConstructorOptions {}
|
||||
|
||||
export interface IGoogleDNSHTTPSResponse {
|
||||
export interface IDnsJsonResponse {
|
||||
Status: number;
|
||||
TC: boolean;
|
||||
RD: boolean;
|
||||
@ -135,14 +135,14 @@ export class Smartdns {
|
||||
): Promise<plugins.tsclass.network.IDnsRecord[]> {
|
||||
const requestUrl = `https://cloudflare-dns.com/dns-query?name=${recordNameArg}&type=${recordTypeArg}&do=1`;
|
||||
const returnArray: plugins.tsclass.network.IDnsRecord[] = [];
|
||||
const getResponseBody = async (counterArg = 0): Promise<IGoogleDNSHTTPSResponse> => {
|
||||
const getResponseBody = async (counterArg = 0): Promise<IDnsJsonResponse> => {
|
||||
const response = await plugins.smartrequest.request(requestUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
accept: 'application/dns-json',
|
||||
},
|
||||
});
|
||||
const responseBody: IGoogleDNSHTTPSResponse = response.body;
|
||||
const responseBody: IDnsJsonResponse = response.body;
|
||||
if (responseBody?.Status !== 0 && counterArg < retriesCounterArg) {
|
||||
await plugins.smartdelay.delayFor(500);
|
||||
return getResponseBody(counterArg++);
|
||||
|
@ -16,7 +16,3 @@ export { smartdelay, smartenv, smartpromise, smartrequest };
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
export { tsclass };
|
||||
|
||||
// third party scope
|
||||
const dns2 = smartenvInstance.getSafeNodeModule('dns2');
|
||||
export { dns2 };
|
||||
|
@ -7,59 +7,61 @@ interface IDnsServerOptions {
|
||||
udpPort: number;
|
||||
}
|
||||
|
||||
class DnsServer {
|
||||
interface IDnsHandler {
|
||||
domainPattern: string;
|
||||
recordTypes: string[];
|
||||
handler: (question: plugins.dnsPacket.Question) => plugins.dnsPacket.Answer | null;
|
||||
}
|
||||
|
||||
export class DnsServer {
|
||||
private udpServer: plugins.dgram.Socket;
|
||||
private httpsServer: plugins.https.Server;
|
||||
private handlers: IDnsHandler[] = [];
|
||||
|
||||
constructor(private options: IDnsServerOptions) {
|
||||
this.udpServer = plugins.dgram.createSocket('udp4');
|
||||
this.setupUdpServer();
|
||||
constructor(private options: IDnsServerOptions) {}
|
||||
|
||||
this.httpsServer = plugins.https.createServer(
|
||||
{
|
||||
key: plugins.fs.readFileSync(options.httpsKey),
|
||||
cert: plugins.fs.readFileSync(options.httpsCert)
|
||||
},
|
||||
this.handleHttpsRequest.bind(this)
|
||||
);
|
||||
public registerHandler(
|
||||
domainPattern: string,
|
||||
recordTypes: string[],
|
||||
handler: (question: plugins.dnsPacket.Question) => plugins.dnsPacket.Answer | null
|
||||
): void {
|
||||
this.handlers.push({ domainPattern, recordTypes, handler });
|
||||
}
|
||||
|
||||
private setupUdpServer(): void {
|
||||
this.udpServer.on('message', (msg, rinfo) => {
|
||||
const request = plugins.dnsPacket.decode(msg);
|
||||
const response = {
|
||||
type: 'response' as const,
|
||||
id: request.id,
|
||||
flags: plugins.dnsPacket.RECURSION_DESIRED | plugins.dnsPacket.RECURSION_AVAILABLE,
|
||||
questions: request.questions,
|
||||
answers: [] as plugins.dnsPacket.Answer[]
|
||||
};
|
||||
private processDnsRequest(request: plugins.dnsPacket.Packet): plugins.dnsPacket.Packet {
|
||||
const response: plugins.dnsPacket.Packet = {
|
||||
type: 'response',
|
||||
id: request.id,
|
||||
flags: plugins.dnsPacket.RECURSION_DESIRED | plugins.dnsPacket.RECURSION_AVAILABLE,
|
||||
questions: request.questions,
|
||||
answers: [],
|
||||
};
|
||||
|
||||
const question = request.questions[0];
|
||||
console.log(`UDP query for ${question.name} of type ${question.type}`);
|
||||
for (const question of request.questions) {
|
||||
console.log(`Query for ${question.name} of type ${question.type}`);
|
||||
|
||||
if (question.type === 'A') {
|
||||
response.answers.push({
|
||||
name: question.name,
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
data: '127.0.0.1'
|
||||
});
|
||||
let answered = false;
|
||||
|
||||
for (const handlerEntry of this.handlers) {
|
||||
if (
|
||||
plugins.minimatch.minimatch(question.name, handlerEntry.domainPattern) &&
|
||||
handlerEntry.recordTypes.includes(question.type)
|
||||
) {
|
||||
const answer = handlerEntry.handler(question);
|
||||
if (answer) {
|
||||
response.answers.push(answer);
|
||||
answered = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const responseData = plugins.dnsPacket.encode(response);
|
||||
this.udpServer.send(responseData, rinfo.port, rinfo.address);
|
||||
});
|
||||
if (!answered) {
|
||||
console.log(`No handler found for ${question.name} of type ${question.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
this.udpServer.on('error', (err) => {
|
||||
console.error(`UDP Server error:\n${err.stack}`);
|
||||
this.udpServer.close();
|
||||
});
|
||||
|
||||
this.udpServer.bind(this.options.udpPort, '0.0.0.0', () => {
|
||||
console.log(`UDP DNS server running on port ${this.options.udpPort}`);
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
private handleHttpsRequest(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse): void {
|
||||
@ -71,27 +73,7 @@ class DnsServer {
|
||||
}).on('end', () => {
|
||||
const msg = Buffer.concat(body);
|
||||
const request = plugins.dnsPacket.decode(msg);
|
||||
const response = {
|
||||
type: 'response' as const,
|
||||
id: request.id,
|
||||
flags: plugins.dnsPacket.RECURSION_DESIRED | plugins.dnsPacket.RECURSION_AVAILABLE,
|
||||
questions: request.questions,
|
||||
answers: [] as plugins.dnsPacket.Answer[]
|
||||
};
|
||||
|
||||
const question = request.questions[0];
|
||||
console.log(`DoH query for ${question.name} of type ${question.type}`);
|
||||
|
||||
if (question.type === 'A') {
|
||||
response.answers.push({
|
||||
name: question.name,
|
||||
type: 'A',
|
||||
class: 'IN',
|
||||
ttl: 300,
|
||||
data: '127.0.0.1'
|
||||
});
|
||||
}
|
||||
|
||||
const response = this.processDnsRequest(request);
|
||||
const responseData = plugins.dnsPacket.encode(response);
|
||||
res.writeHead(200, { 'Content-Type': 'application/dns-message' });
|
||||
res.end(responseData);
|
||||
@ -102,19 +84,64 @@ class DnsServer {
|
||||
}
|
||||
}
|
||||
|
||||
public start(): void {
|
||||
this.httpsServer.listen(this.options.httpsPort, () => {
|
||||
console.log(`DoH server running on port ${this.options.httpsPort}`);
|
||||
public async start(): Promise<void> {
|
||||
this.httpsServer = plugins.https.createServer(
|
||||
{
|
||||
key: this.options.httpsKey,
|
||||
cert: this.options.httpsCert,
|
||||
},
|
||||
this.handleHttpsRequest.bind(this)
|
||||
);
|
||||
|
||||
this.udpServer = plugins.dgram.createSocket('udp4');
|
||||
this.udpServer.on('message', (msg, rinfo) => {
|
||||
const request = plugins.dnsPacket.decode(msg);
|
||||
const response = this.processDnsRequest(request);
|
||||
const responseData = plugins.dnsPacket.encode(response);
|
||||
this.udpServer.send(responseData, rinfo.port, rinfo.address);
|
||||
});
|
||||
|
||||
this.udpServer.on('error', (err) => {
|
||||
console.error(`UDP Server error:\n${err.stack}`);
|
||||
this.udpServer.close();
|
||||
});
|
||||
|
||||
const udpListeningDeferred = plugins.smartpromise.defer<void>();
|
||||
const httpsListeningDeferred = plugins.smartpromise.defer<void>();
|
||||
try {
|
||||
this.udpServer.bind(this.options.udpPort, '0.0.0.0', () => {
|
||||
console.log(`UDP DNS server running on port ${this.options.udpPort}`);
|
||||
udpListeningDeferred.resolve();
|
||||
});
|
||||
|
||||
this.httpsServer.listen(this.options.httpsPort, () => {
|
||||
console.log(`HTTPS DNS server running on port ${this.options.httpsPort}`);
|
||||
httpsListeningDeferred.resolve();
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error starting DNS server:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
await Promise.all([udpListeningDeferred.promise, httpsListeningDeferred.promise]);
|
||||
}
|
||||
|
||||
public stop(): void {
|
||||
public async stop(): Promise<void> {
|
||||
const doneUdp = plugins.smartpromise.defer<void>();
|
||||
const doneHttps = plugins.smartpromise.defer<void>();
|
||||
this.udpServer.close(() => {
|
||||
console.log('UDP DNS server stopped');
|
||||
this.udpServer.unref();
|
||||
this.udpServer = null;
|
||||
doneUdp.resolve();
|
||||
});
|
||||
|
||||
this.httpsServer.close(() => {
|
||||
console.log('HTTPS DNS server stopped');
|
||||
this.httpsServer.unref();
|
||||
this.httpsServer = null;
|
||||
doneHttps.resolve();
|
||||
});
|
||||
|
||||
await Promise.all([doneUdp.promise, doneHttps.promise]);
|
||||
}
|
||||
}
|
172
ts_server/classes.dnstools.ts
Normal file
172
ts_server/classes.dnstools.ts
Normal file
@ -0,0 +1,172 @@
|
||||
// Import necessary plugins from plugins.ts
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
interface DnssecZone {
|
||||
zone: string;
|
||||
algorithm: 'ECDSA' | 'ED25519' | 'RSA';
|
||||
keySize: number;
|
||||
days: number;
|
||||
}
|
||||
|
||||
interface DnssecKeyPair {
|
||||
privateKey: string;
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
export class DnsSec {
|
||||
private zone: DnssecZone;
|
||||
private keyPair: DnssecKeyPair;
|
||||
private ec?: plugins.elliptic.ec; // For ECDSA algorithms
|
||||
private eddsa?: plugins.elliptic.eddsa; // For EdDSA algorithms
|
||||
|
||||
constructor(zone: DnssecZone) {
|
||||
this.zone = zone;
|
||||
|
||||
// Initialize the appropriate cryptographic instance based on the algorithm
|
||||
switch (this.zone.algorithm) {
|
||||
case 'ECDSA':
|
||||
this.ec = new plugins.elliptic.ec('p256'); // Use P-256 curve for ECDSA
|
||||
break;
|
||||
case 'ED25519':
|
||||
this.eddsa = new plugins.elliptic.eddsa('ed25519');
|
||||
break;
|
||||
case 'RSA':
|
||||
// RSA implementation would go here
|
||||
throw new Error('RSA algorithm is not yet implemented.');
|
||||
default:
|
||||
throw new Error(`Unsupported algorithm: ${this.zone.algorithm}`);
|
||||
}
|
||||
|
||||
// Generate the key pair
|
||||
this.keyPair = this.generateKeyPair();
|
||||
}
|
||||
|
||||
private generateKeyPair(): DnssecKeyPair {
|
||||
let privateKey: string;
|
||||
let publicKey: string;
|
||||
|
||||
switch (this.zone.algorithm) {
|
||||
case 'ECDSA':
|
||||
if (!this.ec) throw new Error('EC instance is not initialized.');
|
||||
const ecKeyPair = this.ec.genKeyPair();
|
||||
privateKey = ecKeyPair.getPrivate('hex');
|
||||
publicKey = ecKeyPair.getPublic(false, 'hex'); // Uncompressed format
|
||||
break;
|
||||
case 'ED25519':
|
||||
if (!this.eddsa) throw new Error('EdDSA instance is not initialized.');
|
||||
const secret = plugins.crypto.randomBytes(32);
|
||||
const edKeyPair = this.eddsa.keyFromSecret(secret);
|
||||
privateKey = edKeyPair.getSecret('hex');
|
||||
publicKey = edKeyPair.getPublic('hex');
|
||||
break;
|
||||
case 'RSA':
|
||||
// RSA key generation would be implemented here
|
||||
throw new Error('RSA key generation is not yet implemented.');
|
||||
default:
|
||||
throw new Error(`Unsupported algorithm: ${this.zone.algorithm}`);
|
||||
}
|
||||
|
||||
return { privateKey, publicKey };
|
||||
}
|
||||
|
||||
private getAlgorithmNumber(): number {
|
||||
switch (this.zone.algorithm) {
|
||||
case 'ECDSA':
|
||||
return 13; // ECDSAP256SHA256
|
||||
case 'ED25519':
|
||||
return 15;
|
||||
case 'RSA':
|
||||
return 8; // RSASHA256
|
||||
default:
|
||||
throw new Error(`Unsupported algorithm: ${this.zone.algorithm}`);
|
||||
}
|
||||
}
|
||||
|
||||
public signData(data: Buffer): Buffer {
|
||||
// Sign the data using the private key
|
||||
const keyPair = this.ec!.keyFromPrivate(this.keyPair.privateKey, 'hex');
|
||||
const signature = keyPair.sign(plugins.crypto.createHash('sha256').update(data).digest());
|
||||
return Buffer.from(signature.toDER());
|
||||
}
|
||||
|
||||
private generateDNSKEY(): Buffer {
|
||||
const flags = 256; // 256 indicates a Zone Signing Key (ZSK)
|
||||
const protocol = 3; // Must be 3 according to RFC
|
||||
const algorithm = this.getAlgorithmNumber();
|
||||
|
||||
let publicKeyData: Buffer;
|
||||
|
||||
switch (this.zone.algorithm) {
|
||||
case 'ECDSA':
|
||||
if (!this.ec) throw new Error('EC instance is not initialized.');
|
||||
const ecPublicKey = this.ec.keyFromPublic(this.keyPair.publicKey, 'hex').getPublic();
|
||||
const x = ecPublicKey.getX().toArrayLike(Buffer, 'be', 32);
|
||||
const y = ecPublicKey.getY().toArrayLike(Buffer, 'be', 32);
|
||||
publicKeyData = Buffer.concat([x, y]);
|
||||
break;
|
||||
case 'ED25519':
|
||||
publicKeyData = Buffer.from(this.keyPair.publicKey, 'hex');
|
||||
break;
|
||||
case 'RSA':
|
||||
// RSA public key extraction would go here
|
||||
throw new Error('RSA public key extraction is not yet implemented.');
|
||||
default:
|
||||
throw new Error(`Unsupported algorithm: ${this.zone.algorithm}`);
|
||||
}
|
||||
|
||||
// Construct the DNSKEY RDATA
|
||||
const dnskeyRdata = Buffer.concat([
|
||||
Buffer.from([flags >> 8, flags & 0xff]), // Flags (2 bytes)
|
||||
Buffer.from([protocol]), // Protocol (1 byte)
|
||||
Buffer.from([algorithm]), // Algorithm (1 byte)
|
||||
publicKeyData, // Public Key
|
||||
]);
|
||||
|
||||
return dnskeyRdata;
|
||||
}
|
||||
|
||||
private computeKeyTag(dnskeyRdata: Buffer): number {
|
||||
// Key Tag calculation as per RFC 4034, Appendix B
|
||||
let acc = 0;
|
||||
for (let i = 0; i < dnskeyRdata.length; i++) {
|
||||
acc += i & 1 ? dnskeyRdata[i] : dnskeyRdata[i] << 8;
|
||||
}
|
||||
acc += (acc >> 16) & 0xffff;
|
||||
return acc & 0xffff;
|
||||
}
|
||||
|
||||
private getDNSKEYRecord(): string {
|
||||
const dnskeyRdata = this.generateDNSKEY();
|
||||
const flags = 256;
|
||||
const protocol = 3;
|
||||
const algorithm = this.getAlgorithmNumber();
|
||||
const publicKeyData = dnskeyRdata.slice(4); // Skip flags, protocol, algorithm bytes
|
||||
const publicKeyBase64 = publicKeyData.toString('base64');
|
||||
|
||||
return `${this.zone.zone}. IN DNSKEY ${flags} ${protocol} ${algorithm} ${publicKeyBase64}`;
|
||||
}
|
||||
|
||||
public getDSRecord(): string {
|
||||
const dnskeyRdata = this.generateDNSKEY();
|
||||
const keyTag = this.computeKeyTag(dnskeyRdata);
|
||||
const algorithm = this.getAlgorithmNumber();
|
||||
const digestType = 2; // SHA-256
|
||||
const digest = plugins.crypto
|
||||
.createHash('sha256')
|
||||
.update(dnskeyRdata)
|
||||
.digest('hex')
|
||||
.toUpperCase();
|
||||
|
||||
return `${this.zone.zone}. IN DS ${keyTag} ${algorithm} ${digestType} ${digest}`;
|
||||
}
|
||||
|
||||
public getKeyPair(): DnssecKeyPair {
|
||||
return this.keyPair;
|
||||
}
|
||||
|
||||
public getDsAndKeyPair(): { keyPair: DnssecKeyPair; dsRecord: string; dnskeyRecord: string } {
|
||||
const dsRecord = this.getDSRecord();
|
||||
const dnskeyRecord = this.getDNSKEYRecord();
|
||||
return { keyPair: this.keyPair, dsRecord, dnskeyRecord };
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
export * from './classes.dnsserver.js';
|
@ -1,17 +1,32 @@
|
||||
// node native
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import dgram from 'dgram';
|
||||
|
||||
export {
|
||||
crypto,
|
||||
fs,
|
||||
http,
|
||||
https,
|
||||
dgram,
|
||||
}
|
||||
|
||||
import * as dnsPacket from 'dns-packet';
|
||||
// @push.rocks scope
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
|
||||
export {
|
||||
dnsPacket
|
||||
smartpromise,
|
||||
}
|
||||
|
||||
// third party
|
||||
import * as elliptic from 'elliptic';
|
||||
import * as dnsPacket from 'dns-packet';
|
||||
import * as minimatch from 'minimatch';
|
||||
|
||||
export {
|
||||
dnsPacket,
|
||||
elliptic,
|
||||
minimatch,
|
||||
}
|
||||
|
Reference in New Issue
Block a user