2018-09-09 15:12:39 +00:00
|
|
|
//
|
|
|
|
// ControlChannel.swift
|
|
|
|
// TunnelKit
|
|
|
|
//
|
|
|
|
// Created by Davide De Rosa on 9/9/18.
|
2023-03-17 15:58:36 +00:00
|
|
|
// Copyright (c) 2023 Davide De Rosa. All rights reserved.
|
2018-09-09 15:12:39 +00:00
|
|
|
//
|
2019-05-14 08:58:47 +00:00
|
|
|
// https://github.com/passepartoutvpn
|
2018-09-09 15:12:39 +00:00
|
|
|
//
|
|
|
|
// 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 Foundation
|
2018-09-09 15:31:11 +00:00
|
|
|
import SwiftyBeaver
|
2021-10-25 14:27:27 +00:00
|
|
|
import TunnelKitCore
|
2021-11-07 20:54:05 +00:00
|
|
|
import TunnelKitOpenVPNCore
|
|
|
|
import CTunnelKitCore
|
|
|
|
import CTunnelKitOpenVPNProtocol
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2018-09-09 15:31:11 +00:00
|
|
|
private let log = SwiftyBeaver.self
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
extension OpenVPN {
|
|
|
|
class ControlChannelError: Error, CustomStringConvertible {
|
|
|
|
let description: String
|
|
|
|
|
|
|
|
init(_ message: String) {
|
|
|
|
description = "\(String(describing: ControlChannelError.self))(\(message))"
|
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
}
|
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
class ControlChannel {
|
|
|
|
private let serializer: ControlChannelSerializer
|
|
|
|
|
|
|
|
private(set) var sessionId: Data?
|
|
|
|
|
|
|
|
var remoteSessionId: Data? {
|
|
|
|
didSet {
|
|
|
|
if let id = remoteSessionId {
|
|
|
|
log.debug("Control: Remote sessionId is \(id.toHex())")
|
|
|
|
}
|
2018-09-09 22:58:50 +00:00
|
|
|
}
|
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
private var queue: BidirectionalState<[ControlPacket]>
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
private var currentPacketId: BidirectionalState<UInt32>
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
private var pendingAcks: Set<UInt32>
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
private var plainBuffer: ZeroingData
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
private var dataCount: BidirectionalState<Int>
|
|
|
|
|
|
|
|
convenience init() {
|
|
|
|
self.init(serializer: PlainSerializer())
|
|
|
|
}
|
|
|
|
|
|
|
|
convenience init(withAuthKey key: StaticKey, digest: Digest) throws {
|
|
|
|
self.init(serializer: try AuthSerializer(withKey: key, digest: digest))
|
|
|
|
}
|
2018-09-19 20:15:16 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
convenience init(withCryptKey key: StaticKey) throws {
|
|
|
|
self.init(serializer: try CryptSerializer(withKey: key))
|
|
|
|
}
|
|
|
|
|
|
|
|
private init(serializer: ControlChannelSerializer) {
|
|
|
|
self.serializer = serializer
|
|
|
|
sessionId = nil
|
2018-09-09 15:56:29 +00:00
|
|
|
remoteSessionId = nil
|
2019-05-19 12:04:41 +00:00
|
|
|
queue = BidirectionalState(withResetValue: [])
|
|
|
|
currentPacketId = BidirectionalState(withResetValue: 0)
|
|
|
|
pendingAcks = []
|
|
|
|
plainBuffer = Z(count: TLSBoxMaxBufferLength)
|
|
|
|
dataCount = BidirectionalState(withResetValue: 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func reset(forNewSession: Bool) throws {
|
|
|
|
if forNewSession {
|
|
|
|
try sessionId = SecureRandom.data(length: PacketSessionIdLength)
|
|
|
|
remoteSessionId = nil
|
|
|
|
}
|
|
|
|
queue.reset()
|
|
|
|
currentPacketId.reset()
|
|
|
|
pendingAcks.removeAll()
|
|
|
|
plainBuffer.zero()
|
|
|
|
dataCount.reset()
|
|
|
|
serializer.reset()
|
2018-09-09 15:56:29 +00:00
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func readInboundPacket(withData data: Data, offset: Int) throws -> ControlPacket {
|
|
|
|
let packet = try serializer.deserialize(data: data, start: offset, end: nil)
|
|
|
|
log.debug("Control: Read packet \(packet)")
|
|
|
|
if let ackIds = packet.ackIds as? [UInt32], let ackRemoteSessionId = packet.ackRemoteSessionId {
|
|
|
|
try readAcks(ackIds, acksRemoteSessionId: ackRemoteSessionId)
|
|
|
|
}
|
|
|
|
return packet
|
2018-09-10 09:12:58 +00:00
|
|
|
}
|
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func enqueueInboundPacket(packet: ControlPacket) -> [ControlPacket] {
|
|
|
|
queue.inbound.append(packet)
|
|
|
|
queue.inbound.sort { $0.packetId < $1.packetId }
|
|
|
|
|
|
|
|
var toHandle: [ControlPacket] = []
|
|
|
|
for queuedPacket in queue.inbound {
|
|
|
|
if queuedPacket.packetId < currentPacketId.inbound {
|
|
|
|
queue.inbound.removeFirst()
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if queuedPacket.packetId != currentPacketId.inbound {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
toHandle.append(queuedPacket)
|
|
|
|
|
|
|
|
currentPacketId.inbound += 1
|
2018-09-09 15:31:11 +00:00
|
|
|
queue.inbound.removeFirst()
|
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
return toHandle
|
|
|
|
}
|
|
|
|
|
|
|
|
func enqueueOutboundPackets(withCode code: PacketCode, key: UInt8, payload: Data, maxPacketSize: Int) {
|
|
|
|
guard let sessionId = sessionId else {
|
|
|
|
fatalError("Missing sessionId, do reset(forNewSession: true) first")
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
|
|
|
|
let oldIdOut = currentPacketId.outbound
|
|
|
|
var queuedCount = 0
|
|
|
|
var offset = 0
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
repeat {
|
|
|
|
let subPayloadLength = min(maxPacketSize, payload.count - offset)
|
|
|
|
let subPayloadData = payload.subdata(offset: offset, count: subPayloadLength)
|
|
|
|
let packet = ControlPacket(code: code, key: key, sessionId: sessionId, packetId: currentPacketId.outbound, payload: subPayloadData)
|
|
|
|
|
|
|
|
queue.outbound.append(packet)
|
|
|
|
currentPacketId.outbound += 1
|
|
|
|
offset += maxPacketSize
|
|
|
|
queuedCount += subPayloadLength
|
|
|
|
} while (offset < payload.count)
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
assert(queuedCount == payload.count)
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
// packet count
|
|
|
|
let packetCount = currentPacketId.outbound - oldIdOut
|
|
|
|
if (packetCount > 1) {
|
|
|
|
log.debug("Control: Enqueued \(packetCount) packets [\(oldIdOut)-\(currentPacketId.outbound - 1)]")
|
|
|
|
} else {
|
|
|
|
log.debug("Control: Enqueued 1 packet [\(oldIdOut)]")
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
|
|
|
|
func writeOutboundPackets() throws -> [Data] {
|
|
|
|
var rawList: [Data] = []
|
|
|
|
for packet in queue.outbound {
|
|
|
|
if let sentDate = packet.sentDate {
|
|
|
|
let timeAgo = -sentDate.timeIntervalSinceNow
|
|
|
|
guard (timeAgo >= CoreConfiguration.OpenVPN.retransmissionLimit) else {
|
|
|
|
log.debug("Control: Skip writing packet with packetId \(packet.packetId) (sent on \(sentDate), \(timeAgo) seconds ago)")
|
|
|
|
continue
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
|
|
|
|
log.debug("Control: Write control packet \(packet)")
|
2018-09-10 09:12:58 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
let raw = try serializer.serialize(packet: packet)
|
|
|
|
rawList.append(raw)
|
|
|
|
packet.sentDate = Date()
|
2018-09-09 15:56:29 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
// track pending acks for sent packets
|
|
|
|
pendingAcks.insert(packet.packetId)
|
|
|
|
}
|
|
|
|
// log.verbose("Packets now pending ack: \(pendingAcks)")
|
|
|
|
return rawList
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
|
|
|
|
func hasPendingAcks() -> Bool {
|
|
|
|
return !pendingAcks.isEmpty
|
2018-09-09 15:56:29 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
|
|
|
|
// Ruby: handle_acks
|
|
|
|
private func readAcks(_ packetIds: [UInt32], acksRemoteSessionId: Data) throws {
|
|
|
|
guard let sessionId = sessionId else {
|
2019-05-19 12:19:23 +00:00
|
|
|
throw OpenVPNError.missingSessionId
|
2019-05-19 12:04:41 +00:00
|
|
|
}
|
|
|
|
guard acksRemoteSessionId == sessionId else {
|
|
|
|
log.error("Control: Ack session mismatch (\(acksRemoteSessionId.toHex()) != \(sessionId.toHex()))")
|
2019-05-19 12:19:23 +00:00
|
|
|
throw OpenVPNError.sessionMismatch
|
2019-05-19 12:04:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// drop queued out packets if ack-ed
|
2019-12-22 15:27:43 +00:00
|
|
|
queue.outbound.removeAll {
|
|
|
|
return packetIds.contains($0.packetId)
|
2019-05-19 12:04:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// remove ack-ed packets from pending
|
|
|
|
pendingAcks.subtract(packetIds)
|
|
|
|
|
|
|
|
// log.verbose("Packets still pending ack: \(pendingAcks)")
|
2018-09-09 15:56:29 +00:00
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func writeAcks(withKey key: UInt8, ackPacketIds: [UInt32], ackRemoteSessionId: Data) throws -> Data {
|
|
|
|
guard let sessionId = sessionId else {
|
2019-05-19 12:19:23 +00:00
|
|
|
throw OpenVPNError.missingSessionId
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
2019-05-19 12:04:41 +00:00
|
|
|
let packet = ControlPacket(key: key, sessionId: sessionId, ackIds: ackPacketIds as [NSNumber], ackRemoteSessionId: ackRemoteSessionId)
|
|
|
|
log.debug("Control: Write ack packet \(packet)")
|
|
|
|
return try serializer.serialize(packet: packet)
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func currentControlData(withTLS tls: TLSBox) throws -> ZeroingData {
|
|
|
|
var length = 0
|
|
|
|
try tls.pullRawPlainText(plainBuffer.mutableBytes, length: &length)
|
|
|
|
return plainBuffer.withOffset(0, count: length)
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func addReceivedDataCount(_ count: Int) {
|
|
|
|
dataCount.inbound += count
|
|
|
|
}
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2019-05-19 12:04:41 +00:00
|
|
|
func addSentDataCount(_ count: Int) {
|
|
|
|
dataCount.outbound += count
|
|
|
|
}
|
|
|
|
|
2022-03-04 23:58:07 +00:00
|
|
|
func currentDataCount() -> DataCount {
|
|
|
|
return DataCount(UInt(dataCount.inbound), UInt(dataCount.outbound))
|
2019-05-19 12:04:41 +00:00
|
|
|
}
|
2018-09-09 15:12:39 +00:00
|
|
|
}
|
|
|
|
}
|