aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuard/ConfigFile/WgQuickConfigFileParser.swift
blob: 00a1f9cae6fc51464a722481c2f43e557fda7efd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All rights reserved.

import Foundation

class WgQuickConfigFileParser {

    enum ParserState {
        case inInterfaceSection
        case inPeerSection
        case notInASection
    }

    enum ParseError: Error {
        case invalidLine(_ line: String.SubSequence)
        case noInterface
        case invalidInterface
        case multipleInterfaces
        case invalidPeer
    }

    static func parse(_ text: String, name: String) throws -> TunnelConfiguration {

        assert(!name.isEmpty)

        func collate(interfaceAttributes attributes: [String:String]) -> InterfaceConfiguration? {
            // required wg fields
            guard let privateKeyString = attributes["PrivateKey"] else { return nil }
            guard let privateKey = Data(base64Encoded: privateKeyString), privateKey.count == 32 else { return nil }
            var interface = InterfaceConfiguration(name: name, privateKey: privateKey)
            // other wg fields
            if let listenPortString = attributes["ListenPort"] {
                guard let listenPort = UInt16(listenPortString) else { return nil }
                interface.listenPort = listenPort
            }
            // wg-quick fields
            if let addressesString = attributes["Address"] {
                var addresses: [IPAddressRange] = []
                for addressString in addressesString.split(separator: ",") {
                    let trimmedString = addressString.trimmingCharacters(in: .whitespaces)
                    guard let address = IPAddressRange(from: trimmedString) else { return nil }
                    addresses.append(address)
                }
                interface.addresses = addresses
            }
            if let dnsString = attributes["DNS"] {
                var dnsServers: [DNSServer] = []
                for dnsServerString in dnsString.split(separator: ",") {
                    let trimmedString = dnsServerString.trimmingCharacters(in: .whitespaces)
                    guard let dnsServer = DNSServer(from: trimmedString) else { return nil }
                    dnsServers.append(dnsServer)
                }
                interface.dns = dnsServers
            }
            if let mtuString = attributes["MTU"] {
                guard let mtu = UInt16(mtuString) else { return nil }
                interface.mtu = mtu
            }
            return interface
        }

        func collate(peerAttributes attributes: [String:String]) -> PeerConfiguration? {
            // required wg fields
            guard let publicKeyString = attributes["PublicKey"] else { return nil }
            guard let publicKey = Data(base64Encoded: publicKeyString), publicKey.count == 32 else { return nil }
            var peer = PeerConfiguration(publicKey: publicKey)
            // wg fields
            if let preSharedKeyString = attributes["PreSharedKey"] {
                guard let preSharedKey = Data(base64Encoded: preSharedKeyString), preSharedKey.count == 32 else { return nil }
                peer.preSharedKey = preSharedKey
            }
            if let allowedIPsString = attributes["AllowedIPs"] {
                var allowedIPs: [IPAddressRange] = []
                for allowedIPString in allowedIPsString.split(separator: ",") {
                    let trimmedString = allowedIPString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                    guard let allowedIP = IPAddressRange(from: trimmedString) else { return nil }
                    allowedIPs.append(allowedIP)
                }
                peer.allowedIPs = allowedIPs
            }
            if let endpointString = attributes["Endpoint"] {
                guard let endpoint = Endpoint(from: endpointString) else { return nil }
                peer.endpoint = endpoint
            }
            if let persistentKeepAliveString = attributes["PersistentKeepalive"] {
                guard let persistentKeepAlive = UInt16(persistentKeepAliveString) else { return nil }
                peer.persistentKeepAlive = persistentKeepAlive
            }
            return peer
        }

        var interfaceConfiguration: InterfaceConfiguration? = nil
        var peerConfigurations: [PeerConfiguration] = []

        let lines = text.split(separator: "\n")

        var parserState: ParserState = .notInASection
        var attributes: [String:String] = [:]

        for (lineIndex, line) in lines.enumerated() {
            var trimmedLine: String
            if let commentRange = line.range(of: "#") {
                trimmedLine = String(line[..<commentRange.lowerBound])
            } else {
                trimmedLine = String(line)
            }

            trimmedLine = trimmedLine.trimmingCharacters(in: .whitespaces)

            guard trimmedLine.count > 0 else { continue }
            let lowercasedLine = line.lowercased()

            if let equalsIndex = line.firstIndex(of: "=") {
                // Line contains an attribute
                let key = line[..<equalsIndex].trimmingCharacters(in: .whitespaces)
                let value = line[line.index(equalsIndex, offsetBy: 1)...].trimmingCharacters(in: .whitespaces)
                attributes[key] = value
            } else {
                if (lowercasedLine != "[interface]" && lowercasedLine != "[peer]") {
                    throw ParseError.invalidLine(line)
                }
            }

            let isLastLine: Bool = (lineIndex == lines.count - 1)

            if (isLastLine || lowercasedLine == "[interface]" || lowercasedLine == "[peer]") {
                // Previous section has ended; process the attributes collected so far
                if (parserState == .inInterfaceSection) {
                    guard let interface = collate(interfaceAttributes: attributes) else { throw ParseError.invalidInterface }
                    guard (interfaceConfiguration == nil) else { throw ParseError.multipleInterfaces }
                    interfaceConfiguration = interface
                } else if (parserState == .inPeerSection) {
                    guard let peer = collate(peerAttributes: attributes) else { throw ParseError.invalidPeer }
                    peerConfigurations.append(peer)
                }
            }

            if (lowercasedLine == "[interface]") {
                parserState = .inInterfaceSection
                attributes.removeAll()
            } else if (lowercasedLine == "[peer]") {
                parserState = .inPeerSection
                attributes.removeAll()
            }
        }

        if let interfaceConfiguration = interfaceConfiguration {
            let tunnelConfiguration = TunnelConfiguration(interface: interfaceConfiguration)
            tunnelConfiguration.peers = peerConfigurations
            return tunnelConfiguration
        } else {
            throw ParseError.noInterface
        }
    }
}