Skip to content

Commit bea0492

Browse files
committed
fix mismatch in key encoding
1 parent 3946efb commit bea0492

File tree

4 files changed

+115
-118
lines changed

4 files changed

+115
-118
lines changed

CONTRIBUTORS

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
For the purpose of tracking copyright, this is the list of individuals and
2-
organizations who have contributed source code to LCLPing.
2+
organizations who have contributed source code to LCL.
33

44
### Contributors
55
- Zhennan Zhou

Sources/Command/Measure.swift

Lines changed: 104 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -26,21 +26,23 @@ extension LCLCLI {
2626

2727
func run() async throws {
2828
let encoder: JSONEncoder = JSONEncoder()
29-
30-
// var sites: [CellularSite]
31-
// let result: Result<[CellularSite]?, CLIError> = await NetworkingAPI.get(from: NetworkingAPI.Endpoint.site.url)
32-
// switch result {
33-
// case .failure(let error):
34-
// throw error
35-
// case .success(let cs):
36-
// if let s = cs {
37-
// sites = s
38-
// } else {
39-
// throw CLIError.failedToLoadContent("No cellular site is available. Please check your internet connection or talk to the SCN administrator.")
40-
// }
41-
42-
// }
43-
// var picker = Picker<CellularSite>(title: "Choose the cellular site you are currently at.", options: sites)
29+
encoder.outputFormatting = .sortedKeys
30+
31+
// TODO: prompted picker if the location option is not set
32+
var sites: [CellularSite]
33+
let result: Result<[CellularSite]?, CLIError> = await NetworkingAPI.get(from: NetworkingAPI.Endpoint.site.url)
34+
switch result {
35+
case .failure(let error):
36+
throw error
37+
case .success(let cs):
38+
if let s = cs {
39+
sites = s
40+
} else {
41+
throw CLIError.failedToLoadContent("No cellular site is available. Please check your internet connection or talk to the SCN administrator.")
42+
}
43+
44+
}
45+
var picker = Picker<CellularSite>(title: "Choose the cellular site you are currently at.", options: sites)
4446

4547
let homeURL = FileIO.default.home.appendingPathComponent(".lcl")
4648
let skURL = homeURL.appendingPathComponent("sk")
@@ -49,105 +51,102 @@ extension LCLCLI {
4951
let hpkrURL = homeURL.appendingPathComponent("hpkr")
5052
let keyURL = homeURL.appendingPathComponent("key")
5153
let keyData = try loadData(keyURL)
52-
54+
5355
let symmetricKeyRecovered = SymmetricKey(data: keyData)
5456

55-
let symmetricKey = SymmetricKey(data: keyData)
5657
let skDataEncrypted = try loadData(skURL)
57-
let skData = try decrypt(cipher: skDataEncrypted, key: symmetricKey)
58+
let skData = try decrypt(cipher: skDataEncrypted, key: symmetricKeyRecovered)
5859
let sigDataEncrypted = try loadData(sigURL)
59-
let sigData = try decrypt(cipher: sigDataEncrypted, key: symmetricKey)
60+
let sigData = try decrypt(cipher: sigDataEncrypted, key: symmetricKeyRecovered)
6061
let rDataEncrypted = try loadData(rURL)
61-
let rData = try decrypt(cipher: rDataEncrypted, key: symmetricKey)
62+
let rData = try decrypt(cipher: rDataEncrypted, key: symmetricKeyRecovered)
6263
let hpkrDataEncrypted = try loadData(hpkrURL)
63-
let hpkrData = try decrypt(cipher: hpkrDataEncrypted, key: symmetricKey)
64-
64+
let hpkrData = try decrypt(cipher: hpkrDataEncrypted, key: symmetricKeyRecovered)
6565
let validationResultJSON = try encoder.encode(ValidationResult(R: rData, skT: skData, hPKR: hpkrData))
66+
6667
let ecPrivateKey = try ECDSA.deserializePrivateKey(raw: skData)
6768

68-
// guard try ECDSA.verify(message: validationResultJSON, signature: sigData, publicKey: ecPrivateKey.publicKey) else {
69-
// throw CLIError.contentCorrupted
70-
// }
71-
72-
// let pingOptions = LCLPing.Options()
73-
// let pingConfig = LCLPing.PingConfiguration(type: .icmp, endpoint: .ipv4("google.com", 0))
74-
// let outputFormats: Set<OutputFormat> = [.default]
75-
76-
// var ping = LCLPing(options: pingOptions)
77-
// let speedTest = SpeedTest(testType: .downloadAndUpload)
78-
79-
// signal(SIGINT, SIG_IGN)
80-
// let stopSignal = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
81-
// stopSignal.setEventHandler {
82-
// print("Exit from SCN Measurement Test")
83-
// // picker.exit()
84-
// ping.stop()
85-
// speedTest.stop()
86-
// return
87-
// }
88-
89-
// stopSignal.resume()
90-
91-
// // guard let selectedSite = picker.pick() else {
92-
// // throw CLIError.noCellularSiteSelected
93-
// // }
94-
// let selectedSite = CellularSite(address: "address", cellId: ["a", "b"], latitude: 1.0, longitude: 2.0, name: "name", status: CellularSite.SiteStatus.active)
95-
96-
// let deviceId = UUID().uuidString
97-
98-
// var isPingComplete: Bool = false
99-
// try await ping.start(pingConfiguration: pingConfig)
100-
// switch ping.status {
101-
// case .error, .ready, .running:
102-
// print("Ping Test encountered some error while running tests")
103-
// case .stopped, .finished:
104-
// isPingComplete = true
105-
// }
106-
107-
// let speedTestResults = try await speedTest.run()
108-
// let downloadSummary = prepareSpeedTestSummary(data: speedTestResults.download, unit: .Mbps)
109-
// let uploadSummary = prepareSpeedTestSummary(data: speedTestResults.upload, unit: .Mbps)
110-
// if isPingComplete {
111-
// generatePingSummary(ping.summary, for: .icmp, formats: outputFormats)
112-
// }
113-
// generateSpeedTestSummary(downloadSummary, kind: .download, formats: outputFormats, unit: .Mbps)
114-
// generateSpeedTestSummary(uploadSummary, kind: .upload, formats: outputFormats, unit: .Mbps)
115-
116-
// // MARK: Upload test results to the server
117-
// encoder.outputFormatting = .prettyPrinted
118-
// do {
119-
// let report = ConnectivityReportModel(
120-
// cellId: selectedSite.cellId.first!,
121-
// deviceId: deviceId,
122-
// downloadSpeed: downloadSummary.avg,
123-
// uploadSpeed: uploadSummary.avg,
124-
// latitude: selectedSite.latitude,
125-
// longitude: selectedSite.longitude,
126-
// packetLoss: Double(ping.summary.timeout.count) / Double(ping.summary.totalCount),
127-
// ping: ping.summary.avg,
128-
// timestamp: Date.getCurrentTime(),
129-
// jitter: ping.summary.jitter
130-
// )
131-
// let serialized = try encoder.encode(report)
132-
// let sig_m = try ECDSA.sign(message: serialized, privateKey: ECDSA.deserializePrivateKey(raw: skData))
133-
// let measurementReport = MeasurementReportModel(sigmaM: sig_m.hex, hPKR: hpkrData.hex, M: serialized.hex, showData: showData)
134-
135-
// let reportToSent = try encoder.encode(measurementReport)
136-
// let result = await NetworkingAPI.send(to: NetworkingAPI.Endpoint.report.url, using: reportToSent)
137-
// switch result {
138-
// case .success:
139-
// print("Data reported successfully.")
140-
// case .failure(let error):
141-
// print("Data report failed with error: \(error)")
142-
// }
143-
print("DONE!")
144-
// } catch EncodingError.invalidValue {
145-
// print("Measurement data is corruptted.")
146-
// } catch let error as LCLAuthError {
147-
// print("Registration info is corruptted. \(error)")
148-
// } catch {
149-
// print("Data report failed with error: \(error)")
150-
// }
69+
guard try ECDSA.verify(message: validationResultJSON, signature: sigData, publicKey: ecPrivateKey.publicKey) else {
70+
throw CLIError.contentCorrupted
71+
}
72+
73+
let pingOptions = LCLPing.Options()
74+
let pingConfig = LCLPing.PingConfiguration(type: .icmp, endpoint: .ipv4("google.com", 0))
75+
let outputFormats: Set<OutputFormat> = [.default]
76+
77+
var ping = LCLPing(options: pingOptions)
78+
let speedTest = SpeedTest(testType: .downloadAndUpload)
79+
80+
signal(SIGINT, SIG_IGN)
81+
let stopSignal = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
82+
stopSignal.setEventHandler {
83+
print("Exit from SCN Measurement Test")
84+
// picker.exit()
85+
ping.stop()
86+
speedTest.stop()
87+
return
88+
}
89+
90+
stopSignal.resume()
91+
92+
guard let selectedSite = picker.pick() else {
93+
throw CLIError.noCellularSiteSelected
94+
}
95+
96+
let deviceId = UUID().uuidString
97+
98+
var isPingComplete: Bool = false
99+
try await ping.start(pingConfiguration: pingConfig)
100+
switch ping.status {
101+
case .error, .ready, .running:
102+
print("Ping Test encountered some error while running tests")
103+
case .stopped, .finished:
104+
isPingComplete = true
105+
}
106+
107+
let speedTestResults = try await speedTest.run()
108+
let downloadSummary = prepareSpeedTestSummary(data: speedTestResults.download, unit: .Mbps)
109+
let uploadSummary = prepareSpeedTestSummary(data: speedTestResults.upload, unit: .Mbps)
110+
if isPingComplete {
111+
generatePingSummary(ping.summary, for: .icmp, formats: outputFormats)
112+
}
113+
generateSpeedTestSummary(downloadSummary, kind: .download, formats: outputFormats, unit: .Mbps)
114+
generateSpeedTestSummary(uploadSummary, kind: .upload, formats: outputFormats, unit: .Mbps)
115+
116+
// MARK: Upload test results to the server
117+
encoder.outputFormatting = .prettyPrinted
118+
do {
119+
let report = ConnectivityReportModel(
120+
cellId: selectedSite.cellId.first!,
121+
deviceId: deviceId,
122+
downloadSpeed: downloadSummary.avg,
123+
uploadSpeed: uploadSummary.avg,
124+
latitude: selectedSite.latitude,
125+
longitude: selectedSite.longitude,
126+
packetLoss: Double(ping.summary.timeout.count) / Double(ping.summary.totalCount),
127+
ping: ping.summary.avg,
128+
timestamp: Date.getCurrentTime(),
129+
jitter: ping.summary.jitter
130+
)
131+
let serialized = try encoder.encode(report)
132+
let sig_m = try ECDSA.sign(message: serialized, privateKey: ECDSA.deserializePrivateKey(raw: skData))
133+
let measurementReport = MeasurementReportModel(sigmaM: sig_m.hex, hPKR: hpkrData.hex, M: serialized.hex, showData: showData)
134+
135+
let reportToSent = try encoder.encode(measurementReport)
136+
let result = await NetworkingAPI.send(to: NetworkingAPI.Endpoint.report.url, using: reportToSent)
137+
switch result {
138+
case .success:
139+
print("Data reported successfully.")
140+
case .failure(let error):
141+
print("Data report failed with error: \(error)")
142+
}
143+
} catch EncodingError.invalidValue {
144+
print("Measurement data is corruptted.")
145+
} catch let error as LCLAuthError {
146+
print("Registration info is corruptted. \(error)")
147+
} catch {
148+
print("Data report failed with error: \(error)")
149+
}
151150
}
152151

153152
private func loadData(_ from: URL) throws -> Data {
@@ -156,11 +155,5 @@ extension LCLCLI {
156155
}
157156
return data
158157
}
159-
160-
private func encryptAndWriteData(_ data: Data, to fileURL: URL, using key: SymmetricKey) throws {
161-
var data = try LCLAuth.encrypt(plainText: data, key: key)
162-
try FileIO.default.write(data: data, to: fileURL)
163-
data.removeAll()
164-
}
165158
}
166159
}

Sources/Command/RegisterCommand.swift

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ extension LCLCLI {
7171
}
7272
}
7373

74+
let encoder: JSONEncoder = JSONEncoder()
75+
encoder.outputFormatting = .sortedKeys
7476
let validationResult = try LCLAuth.validate(credential: credentialCode)
7577
var outputData = Data()
7678
outputData.append(validationResult.skT)
@@ -84,15 +86,15 @@ extension LCLCLI {
8486
let h_concat = Data(outputData)
8587
let sigma_r = try ECDSA.sign(message: h_concat, privateKey: sk_t)
8688
let registration = RegistrationModel(sigmaR: sigma_r.hex, h: h_concat.hex, R: validationResult.R.hex)
87-
let registrationJson = try JSONEncoder().encode(registration)
89+
let registrationJson = try encoder.encode(registration)
8890
switch await NetworkingAPI.send(to: NetworkingAPI.Endpoint.register.url, using: registrationJson) {
8991
case .success:
9092
print("Registration complete!")
9193
case .failure(let error):
9294
throw CLIError.failedToRegister(error)
9395
}
9496

95-
let validationJson = try JSONEncoder().encode(validationResult)
97+
let validationJson = try encoder.encode(validationResult)
9698
let privateKey = try ECDSA.deserializePrivateKey(raw: validationResult.skT)
9799
let signature = try ECDSA.sign(message: validationJson, privateKey: privateKey)
98100

@@ -110,9 +112,9 @@ extension LCLCLI {
110112
}
111113

112114
private func encryptAndWriteData(_ data: Data, to fileURL: URL, using key: SymmetricKey) throws {
113-
var data = try LCLAuth.encrypt(plainText: data, key: key)
114-
try FileIO.default.write(data: data, to: fileURL)
115-
data.removeAll()
115+
var encrypted = try LCLAuth.encrypt(plainText: data, key: key)
116+
try FileIO.default.write(data: encrypted, to: fileURL)
117+
encrypted.removeAll()
116118
}
117119
}
118120
}

Sources/IO/IO+File.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ class FileIO {
9999
}
100100

101101
func remove(at fileURL: URL) throws {
102-
try self.fileManager.removeItem(atPath: fileURL.relativePath)
102+
if fileExists(fileURL) {
103+
try self.fileManager.removeItem(atPath: fileURL.relativePath)
104+
}
103105
}
104106
}

0 commit comments

Comments
 (0)