Skip to content
This repository has been archived by the owner on Sep 29, 2024. It is now read-only.

Convert encryption tests to proper unit tests #348

Merged
merged 4 commits into from
Dec 13, 2023
Merged
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 Sources/CTunnelKitCore/ZeroingData.m
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ - (instancetype)initWithCount:(NSInteger)count
if ((self = [super init])) {
_count = count;
_bytes = allocate_safely(count);
bzero(_bytes, _count);
}
return self;
}
Expand Down
29 changes: 18 additions & 11 deletions Sources/CTunnelKitOpenVPNProtocol/CryptoCBC.m
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,15 @@ - (BOOL)encryptBytes:(const uint8_t *)bytes length:(NSInteger)length dest:(uint8
int code = 1;

if (self.cipher) {
if (RAND_bytes(outIV, self.cipherIVLength) != 1) {
if (error) {
*error = OpenVPNErrorWithCode(OpenVPNErrorCodeCryptoRandomGenerator);
if (!flags || !flags->forTesting) {
if (RAND_bytes(outIV, self.cipherIVLength) != 1) {
if (error) {
*error = OpenVPNErrorWithCode(OpenVPNErrorCodeCryptoRandomGenerator);
}
return NO;
}
return NO;
}

TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherInit(self.cipherCtxEnc, NULL, NULL, outIV, -1);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherUpdate(self.cipherCtxEnc, outEncrypted, &l1, bytes, (int)length);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherFinal_ex(self.cipherCtxEnc, outEncrypted + l1, &l2);
Expand Down Expand Up @@ -203,8 +205,6 @@ - (void)configureDecryptionWithCipherKey:(ZeroingData *)cipherKey hmacKey:(Zeroi

- (BOOL)decryptBytes:(const uint8_t *)bytes length:(NSInteger)length dest:(uint8_t *)dest destLength:(NSInteger *)destLength flags:(const CryptoFlags * _Nullable)flags error:(NSError * _Nullable __autoreleasing * _Nullable)error
{
NSAssert(self.cipher, @"No cipher provided");

const uint8_t *iv = bytes + self.digestLength;
const uint8_t *encrypted = bytes + self.digestLength + self.cipherIVLength;
int l1 = 0, l2 = 0;
Expand All @@ -221,11 +221,18 @@ - (BOOL)decryptBytes:(const uint8_t *)bytes length:(NSInteger)length dest:(uint8
return NO;
}

TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherInit(self.cipherCtxDec, NULL, NULL, iv, -1);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherUpdate(self.cipherCtxDec, dest, &l1, encrypted, (int)length - self.digestLength - self.cipherIVLength);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherFinal_ex(self.cipherCtxDec, dest + l1, &l2);
if (self.cipher) {
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherInit(self.cipherCtxDec, NULL, NULL, iv, -1);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherUpdate(self.cipherCtxDec, dest, &l1, encrypted, (int)length - self.digestLength - self.cipherIVLength);
TUNNEL_CRYPTO_TRACK_STATUS(code) EVP_CipherFinal_ex(self.cipherCtxDec, dest + l1, &l2);

*destLength = l1 + l2;
} else {
l2 = (int)length - l1;
memcpy(dest, bytes + l1, l2);

*destLength = l1 + l2;
*destLength = l2;
}

TUNNEL_CRYPTO_RETURN_STATUS(code)
}
Expand Down
1 change: 1 addition & 0 deletions Sources/CTunnelKitOpenVPNProtocol/include/Crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ typedef struct {
NSInteger ivLength;
const uint8_t *_Nullable ad;
NSInteger adLength;
BOOL forTesting;
} CryptoFlags;

// WARNING: dest must be able to hold ciphertext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ extension OpenVPN.ControlChannel {
var decryptedCount = 0
try packet.withUnsafeBytes {
let src = $0.bytePointer
var flags = CryptoFlags(iv: nil, ivLength: 0, ad: src, adLength: adLength)
var flags = CryptoFlags(iv: nil, ivLength: 0, ad: src, adLength: adLength, forTesting: false)
try decryptedPacket.withUnsafeMutableBytes {
let dest = $0.bytePointer
try decrypter.decryptBytes(src + flags.adLength, length: encryptedCount, dest: dest + headerLength, destLength: &decryptedCount, flags: &flags)
Expand Down
7 changes: 0 additions & 7 deletions Tests/TunnelKitCoreTests/RandomTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,8 @@ class RandomTests: XCTestCase {
}

func testRandom1() {
print(try! SecureRandom.uint32())
print(try! SecureRandom.uint32())
print(try! SecureRandom.uint32())
print(try! SecureRandom.uint32())
print(try! SecureRandom.uint32())
}

func testRandom2() {
print("random UInt32: \(try! SecureRandom.uint32())")
print("random bytes: \(try! SecureRandom.data(length: 12).toHex())")
}
}
8 changes: 0 additions & 8 deletions Tests/TunnelKitCoreTests/RoutingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class RoutingTests: XCTestCase {

func testEntryMatch4() {
let entry24 = RoutingTableEntry(iPv4Network: "192.168.1.0/24", gateway: nil, networkInterface: "en0")
print(entry24.networkMask()!)
for i in 0x0...0xff {
XCTAssertTrue(entry24.matchesDestination("192.168.1.\(i)"))
}
Expand All @@ -47,7 +46,6 @@ class RoutingTests: XCTestCase {
}

let entry28 = RoutingTableEntry(iPv4Network: "192.168.1.0/28", gateway: nil, networkInterface: "en0")
print(entry28.networkMask()!)
for i in 0x0...0xf {
XCTAssertTrue(entry28.matchesDestination("192.168.1.\(i)"))
}
Expand All @@ -70,13 +68,10 @@ class RoutingTests: XCTestCase {
let table = RoutingTable()

for entry in table.ipv4() {
print(entry)
}

if let defaultGateway = table.defaultGateway4()?.gateway() {
print("Default gateway: \(defaultGateway)")
if let lan = table.broadestRoute4(matchingDestination: defaultGateway) {
print("Gateway LAN: \(lan.network())/\(lan.prefix())")
}
}
}
Expand All @@ -85,13 +80,10 @@ class RoutingTests: XCTestCase {
let table = RoutingTable()

for entry in table.ipv6() {
print(entry)
}

if let defaultGateway = table.defaultGateway6()?.gateway() {
print("Default gateway: \(defaultGateway)")
if let lan = table.broadestRoute6(matchingDestination: defaultGateway) {
print("Gateway LAN: \(lan.network())/\(lan.prefix())")
}
}
}
Expand Down
3 changes: 0 additions & 3 deletions Tests/TunnelKitLZOTests/CompressionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ class CompressionTests: XCTestCase {

override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// print("LZO version: \(LZO.versionString())")
}

override func tearDown() {
Expand All @@ -51,8 +50,6 @@ class CompressionTests: XCTestCase {
XCTFail("Unable to decompress data")
return
}
print("BEFORE: \(src)")
print("AFTER : \(dstDecompressed)")
XCTAssertEqual(src, dstDecompressed)
}
}
10 changes: 3 additions & 7 deletions Tests/TunnelKitOpenVPNTests/AppExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ class AppExtensionTests: XCTestCase {
guard let pc = proto.providerConfiguration else {
return
}
print("\(pc)")

let ovpn = pc["configuration"] as? [String: Any]
XCTAssertEqual(pc["appGroup"] as? String, appGroup)
Expand All @@ -107,11 +106,11 @@ class AppExtensionTests: XCTestCase {
exp.fulfill()
}
switch $0 {
case .success(let records):
print("\(records)")
case .success:
break

case .failure:
print("Can't resolve")
break
}
}
waitForExpectations(timeout: 5.0, handler: nil)
Expand Down Expand Up @@ -159,7 +158,6 @@ class AppExtensionTests: XCTestCase {
guard let remote = strategy.currentRemote else {
break
}
print("\(i): \(remote)")
XCTAssertEqual(remote.originalEndpoint.description, expected[i])
i += 1
guard strategy.tryNextEndpoint() else {
Expand Down Expand Up @@ -190,7 +188,6 @@ class AppExtensionTests: XCTestCase {
// var i = 0
// while strategy.hasEndpoint() {
// let endpoint = strategy.currentEndpoint()
// print("\(endpoint)")
// XCTAssertEqual(endpoint.description, expected[i])
// i += 1
// strategy.tryNextEndpoint()
Expand Down Expand Up @@ -219,7 +216,6 @@ class AppExtensionTests: XCTestCase {
// var i = 0
// while strategy.hasEndpoint() {
// let endpoint = strategy.currentEndpoint()
// print("\(endpoint)")
// XCTAssertEqual(endpoint.description, expected[i])
// i += 1
// strategy.tryNextEndpoint()
Expand Down
3 changes: 1 addition & 2 deletions Tests/TunnelKitOpenVPNTests/ConfigurationParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ class ConfigurationParserTests: XCTestCase {

func testStripped() throws {
let lines = try OpenVPN.ConfigurationParser.parsed(fromURL: url(withName: "pia-hungary"), returnsStripped: true).strippedLines!
let stripped = lines.joined(separator: "\n")
print(stripped)
_ = lines.joined(separator: "\n")
}

func testEncryptedCertificateKey() throws {
Expand Down
5 changes: 0 additions & 5 deletions Tests/TunnelKitOpenVPNTests/ControlChannelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ class ControlChannelTests: XCTestCase {
let hmac = Data(hex: "e67c9137933a412a711c0d0514aca6db6476d17d")
let subject = Data(hex: "000000015b96c94738858fe14742fdae400000000000")
let data = hmac + subject
print(data.toHex())

XCTAssertNoThrow(try server.decrypter().verifyData(data, flags: nil))
}
Expand Down Expand Up @@ -98,8 +97,6 @@ class ControlChannelTests: XCTestCase {
XCTAssertNil(error)
return
}
print("raw: \(raw.toHex())")
print("org: \(original.toHex())")
XCTAssertEqual(raw, original)
}

Expand Down Expand Up @@ -130,8 +127,6 @@ class ControlChannelTests: XCTestCase {
XCTAssertNil(error)
return
}
print("raw: \(raw.toHex())")
print("org: \(original.toHex())")
XCTAssertEqual(raw, original)
}
}
75 changes: 75 additions & 0 deletions Tests/TunnelKitOpenVPNTests/CryptoAEADTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//
// CryptoAEADTests.swift
// TunnelKitOpenVPNTests
//
// Created by Davide De Rosa on 12/12/23.
// Copyright (c) 2023 Davide De Rosa. All rights reserved.
//
// https://github.com/passepartoutvpn
//
// This file is part of TunnelKit.
//
// TunnelKit is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// TunnelKit is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with TunnelKit. If not, see <http://www.gnu.org/licenses/>.
//

import XCTest
@testable import TunnelKitCore
@testable import TunnelKitOpenVPNCore
import CTunnelKitCore
import CTunnelKitOpenVPNProtocol

class CryptoAEADTests: XCTestCase {
private let cipherKey = ZeroingData(count: 32)

private let hmacKey = ZeroingData(count: 32)

private let plainData = Data(hex: "00112233ffddaa")

func test_givenData_whenEncrypt_thenDecrypts() {
let encryptedData: Data
var flags = cryptoFlags

let sut1 = CryptoAEAD(cipherName: "aes-256-gcm")
sut1.configureEncryption(withCipherKey: cipherKey, hmacKey: hmacKey)
do {
encryptedData = try sut1.encryptData(plainData, flags: &flags)
} catch {
XCTFail("Cannot encrypt: \(error)")
return
}

let sut2 = CryptoAEAD(cipherName: "aes-256-gcm")
sut2.configureDecryption(withCipherKey: cipherKey, hmacKey: hmacKey)
do {
let returnedData = try sut2.decryptData(encryptedData, flags: &flags)
XCTAssertEqual(returnedData, plainData)
} catch {
XCTFail("Cannot decrypt: \(error)")
}
}

private var cryptoFlags: CryptoFlags {
let packetId: [UInt8] = [0x56, 0x34, 0x12, 0x00]
let ad: [UInt8] = [0x00, 0x12, 0x34, 0x56]
return packetId.withUnsafeBufferPointer { iv in
ad.withUnsafeBufferPointer { ad in
CryptoFlags(iv: iv.baseAddress,
ivLength: packetId.count,
ad: ad.baseAddress,
adLength: ad.count,
forTesting: true)
}
}
}
}
Loading