Prevent SSRF via IMAP/SMTP/CalDAV (#17973)
Prevents leaking of internal services by filtering out private IPs, same way we do for webhooks
This commit is contained in:
+1
-1
@@ -107,7 +107,7 @@ export class ImapSmtpCaldavResolver {
|
||||
|
||||
if (params) {
|
||||
validatedParams[protocol] =
|
||||
this.mailConnectionValidatorService.validateProtocolConnectionParams(
|
||||
await this.mailConnectionValidatorService.validateProtocolConnectionParams(
|
||||
params,
|
||||
);
|
||||
const validatedProtocolParams = validatedParams[protocol];
|
||||
|
||||
+3
@@ -1,8 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { SecureHttpClientModule } from 'src/engine/core-modules/secure-http-client/secure-http-client.module';
|
||||
|
||||
import { ImapSmtpCaldavValidatorService } from './imap-smtp-caldav-connection-validator.service';
|
||||
|
||||
@Module({
|
||||
imports: [SecureHttpClientModule],
|
||||
providers: [ImapSmtpCaldavValidatorService],
|
||||
exports: [ImapSmtpCaldavValidatorService],
|
||||
})
|
||||
|
||||
+25
-3
@@ -4,10 +4,15 @@ import { msg } from '@lingui/core/macro';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
|
||||
import { type ConnectionParameters } from 'src/engine/core-modules/imap-smtp-caldav-connection/types/imap-smtp-caldav-connection.type';
|
||||
|
||||
@Injectable()
|
||||
export class ImapSmtpCaldavValidatorService {
|
||||
constructor(
|
||||
private readonly secureHttpClientService: SecureHttpClientService,
|
||||
) {}
|
||||
|
||||
private readonly protocolConnectionSchema = z.object({
|
||||
host: z.string().min(1, 'Host is required'),
|
||||
port: z.int().positive('Port must be a positive number'),
|
||||
@@ -16,9 +21,9 @@ export class ImapSmtpCaldavValidatorService {
|
||||
secure: z.boolean().optional(),
|
||||
});
|
||||
|
||||
validateProtocolConnectionParams(
|
||||
async validateProtocolConnectionParams(
|
||||
params: ConnectionParameters,
|
||||
): ConnectionParameters {
|
||||
): Promise<ConnectionParameters> {
|
||||
if (!params) {
|
||||
throw new UserInputError('Protocol connection parameters are required', {
|
||||
userFriendlyMessage: msg`Please provide connection details to configure your email account.`,
|
||||
@@ -26,8 +31,25 @@ export class ImapSmtpCaldavValidatorService {
|
||||
}
|
||||
|
||||
try {
|
||||
return this.protocolConnectionSchema.parse(params);
|
||||
const validated = this.protocolConnectionSchema.parse(params);
|
||||
|
||||
try {
|
||||
await this.secureHttpClientService.getValidatedHost(validated.host);
|
||||
} catch {
|
||||
throw new UserInputError(
|
||||
'Connection to private or internal network addresses is not allowed',
|
||||
{
|
||||
userFriendlyMessage: msg`The server address you entered is not allowed. Please use a public server address.`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return validated;
|
||||
} catch (error) {
|
||||
if (error instanceof UserInputError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
const errorMessages = error.issues
|
||||
.map((err) => `${err.path.join('.')}: ${err.message}`)
|
||||
|
||||
+25
@@ -3,6 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import axios, { type AxiosInstance, type CreateAxiosDefaults } from 'axios';
|
||||
|
||||
import { createSsrfSafeAgent } from 'src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util';
|
||||
import { resolveAndValidateHostname } from 'src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util';
|
||||
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
|
||||
|
||||
import { type OutboundRequestContext } from './outbound-request-context.type';
|
||||
@@ -60,4 +61,28 @@ export class SecureHttpClientService {
|
||||
getInternalHttpClient(config?: CreateAxiosDefaults): AxiosInstance {
|
||||
return axios.create(config);
|
||||
}
|
||||
|
||||
async getValidatedHost(hostnameOrUrl: string): Promise<string> {
|
||||
if (!this.isSafeModeEnabled()) {
|
||||
return hostnameOrUrl;
|
||||
}
|
||||
|
||||
return resolveAndValidateHostname(hostnameOrUrl);
|
||||
}
|
||||
|
||||
async getValidatedUrl(serverUrl: string): Promise<string> {
|
||||
if (!this.isSafeModeEnabled()) {
|
||||
return serverUrl;
|
||||
}
|
||||
const resolvedIp = await resolveAndValidateHostname(serverUrl);
|
||||
const url = new URL(serverUrl);
|
||||
|
||||
url.hostname = resolvedIp;
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private isSafeModeEnabled(): boolean {
|
||||
return this.twentyConfigService.get('OUTBOUND_HTTP_SAFE_MODE_ENABLED');
|
||||
}
|
||||
}
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import { resolveAndValidateHostname } from 'src/engine/core-modules/secure-http-client/utils/resolve-and-validate-hostname.util';
|
||||
|
||||
describe('resolveAndValidateHostname', () => {
|
||||
let mockDnsLookup: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockDnsLookup = jest.fn();
|
||||
});
|
||||
|
||||
it('should resolve a plain hostname and pass it to DNS lookup', async () => {
|
||||
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
|
||||
|
||||
await resolveAndValidateHostname('imap.fastmail.com', mockDnsLookup);
|
||||
|
||||
expect(mockDnsLookup).toHaveBeenCalledWith('imap.fastmail.com');
|
||||
});
|
||||
|
||||
it('should extract hostname from a full URL before resolving', async () => {
|
||||
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
|
||||
|
||||
await resolveAndValidateHostname(
|
||||
'https://caldav.example.com:8443/dav/principals',
|
||||
mockDnsLookup,
|
||||
);
|
||||
|
||||
expect(mockDnsLookup).toHaveBeenCalledWith('caldav.example.com');
|
||||
});
|
||||
|
||||
it('should throw when the resolved IP is private', async () => {
|
||||
mockDnsLookup.mockResolvedValue({ address: '10.0.0.1', family: 4 });
|
||||
|
||||
await expect(
|
||||
resolveAndValidateHostname('evil.example.com', mockDnsLookup),
|
||||
).rejects.toThrow(
|
||||
'Connection to internal IP address 10.0.0.1 is not allowed.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return the resolved public IP', async () => {
|
||||
mockDnsLookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
|
||||
|
||||
const result = await resolveAndValidateHostname(
|
||||
'mail.example.com',
|
||||
mockDnsLookup,
|
||||
);
|
||||
|
||||
expect(result).toBe('93.184.216.34');
|
||||
});
|
||||
|
||||
it('should propagate DNS resolution failures', async () => {
|
||||
mockDnsLookup.mockRejectedValue(
|
||||
new Error('getaddrinfo ENOTFOUND bogus.invalid'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
resolveAndValidateHostname('bogus.invalid', mockDnsLookup),
|
||||
).rejects.toThrow('getaddrinfo ENOTFOUND bogus.invalid');
|
||||
});
|
||||
});
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import * as dns from 'dns/promises';
|
||||
|
||||
import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';
|
||||
|
||||
export const resolveAndValidateHostname = async (
|
||||
hostnameOrUrl: string,
|
||||
dnsLookup: typeof dns.lookup = dns.lookup,
|
||||
): Promise<string> => {
|
||||
let hostname: string;
|
||||
|
||||
try {
|
||||
const url = new URL(hostnameOrUrl);
|
||||
|
||||
hostname = url.hostname;
|
||||
} catch {
|
||||
hostname = hostnameOrUrl;
|
||||
}
|
||||
|
||||
const { address: resolvedIp } = await dnsLookup(hostname);
|
||||
|
||||
if (isPrivateIp(resolvedIp)) {
|
||||
throw new Error(
|
||||
`Connection to internal IP address ${resolvedIp} is not allowed.`,
|
||||
);
|
||||
}
|
||||
|
||||
return resolvedIp;
|
||||
};
|
||||
@@ -72,7 +72,7 @@ export class ConfigVariables {
|
||||
@ConfigVariablesMetadata({
|
||||
group: ConfigVariablesGroup.OTHER,
|
||||
description:
|
||||
'Enable safe mode for outbound HTTP requests (prevents private IPs and other security risks). Applies to HTTP workflow actions and webhooks.',
|
||||
'Enable safe mode for outbound requests (prevents private IPs and other security risks). Applies to HTTP workflow actions, webhooks, and IMAP/SMTP/CalDAV connections.',
|
||||
type: ConfigVariableType.BOOLEAN,
|
||||
})
|
||||
@IsOptional()
|
||||
|
||||
Reference in New Issue
Block a user