-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathPassword.swift
229 lines (193 loc) · 7.55 KB
/
Password.swift
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//
// Password.swift
// passKit
//
// Created by Mingshen Sun on 2/2/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import Base32
import OneTimePassword
public class Password {
public var name: String
public var path: String
public var plainText: String
public var changed: Int = 0
public var otpType: OTPType = .none
private var parser = Parser(plainText: "")
private var additions = [AdditionField]()
private var firstLineIsOTPField = false
private var otpToken: Token? {
didSet {
otpType = OTPType(token: otpToken)
}
}
public var namePath: String {
(path as NSString).deletingPathExtension
}
public var nameFromPath: String? {
URL(string: path)?.deletingPathExtension().pathComponents.last
}
public var password: String {
parser.firstLine
}
public var plainData: Data {
plainText.data(using: .utf8)!
}
public var additionsPlainText: String {
parser.additionsSection
}
public var username: String? {
getAdditionValue(withKey: Constants.USERNAME_KEYWORD)
}
public var user: String? {
getAdditionValue(withKey: Constants.USER_KEYWORD)
}
public var login: String? {
getAdditionValue(withKey: Constants.LOGIN_KEYWORD)
}
public var urlString: String? {
getAdditionValue(withKey: Constants.URL_KEYWORD)
}
public var currentOtp: String? {
otpToken?.currentPassword
}
public var numberOfUnknowns: Int {
additions.map(\.title).filter(Constants.isUnknown).count
}
public var numberOfOtpRelated: Int {
additions.map(\.title).filter(Constants.isOtpKeyword).count - (firstLineIsOTPField ? 1 : 0)
}
public init(name: String, path: String, plainText: String) {
self.name = name
self.path = path
self.plainText = plainText
initEverything()
}
public func fileURL(in directoryURL: URL) -> URL {
directoryURL.appendingPathComponent(path)
}
public func updatePassword(name: String, path: String, plainText: String) {
guard self.plainText != plainText || self.path != path else {
return
}
if self.plainText != plainText {
self.plainText = plainText
changed |= PasswordChange.content.rawValue
}
if self.path != path {
self.path = path
changed |= PasswordChange.path.rawValue
}
self.name = name
initEverything()
}
private func initEverything() {
parser = Parser(plainText: plainText)
additions = parser.additionFields
// Check whether the first line looks like an otp entry.
checkPasswordForOtpToken()
// Construct the otp token.
updateOtpToken()
}
private func checkPasswordForOtpToken() {
let (key, value) = Parser.getKeyValuePair(from: password)
if let key, Constants.isOtpKeyword(key) {
firstLineIsOTPField = true
additions.append(key => value)
} else {
firstLineIsOTPField = false
}
}
public func getFilteredAdditions() -> [AdditionField] {
additions.filter { field in
let title = field.title.lowercased()
return title != Constants.USERNAME_KEYWORD
&& title != Constants.USER_KEYWORD
&& title != Constants.LOGIN_KEYWORD
&& title != Constants.PASSWORD_KEYWORD
&& (!Constants.isUnknown(title) || !Defaults.isHideUnknownOn)
&& (!Constants.isOtpKeyword(title) || !Defaults.isHideOTPOn)
}
}
private func getAdditionValue(withKey key: String, caseSensitive: Bool = false) -> String? {
let toLowercase = { (string: String) -> String in caseSensitive ? string : string.lowercased() }
return additions.first { toLowercase($0.title) == toLowercase(key) }?.content
}
/// Set the OTP token if we are able to construct a valid one.
///
/// Example of TOTP otpauth:
///
/// otpauth://totp/totp-secret?secret=AAAAAAAAAAAAAAAA&issuer=totp-secret
///
/// See also [Key URI Format](https://github.com/google/google-authenticator/wiki/Key-URI-Format).
///
/// In case no otpauth is given in the password file, try to construct the token from separate fields using a
/// `TokenBuilder`. This means that tokens provided as otpauth have higher priority.
///
private func updateOtpToken() {
// Get otpauth. If we are able to generate a token, return.
if var otpauthString = getAdditionValue(withKey: Constants.OTPAUTH, caseSensitive: true) {
if !otpauthString.hasPrefix("\(Constants.OTPAUTH):") {
otpauthString = "\(Constants.OTPAUTH):\(otpauthString)"
}
if let otpauthURL = URL(string: otpauthString), let token = Token(url: otpauthURL) {
otpToken = token
return
}
}
// Construct OTP token from separate fields provided in the password file.
otpToken = TokenBuilder()
.usingName(name)
.usingSecret(getAdditionValue(withKey: Constants.OTP_SECRET))
.usingType(getAdditionValue(withKey: Constants.OTP_TYPE))
.usingAlgorithm(getAdditionValue(withKey: Constants.OTP_ALGORITHM))
.usingDigits(getAdditionValue(withKey: Constants.OTP_DIGITS))
.usingPeriod(getAdditionValue(withKey: Constants.OTP_PERIOD))
.usingCounter(getAdditionValue(withKey: Constants.OTP_COUNTER))
.usingRepresentation(getAdditionValue(withKey: Constants.OTP_REPRESENTATION))
.build()
}
/// Get the OTP description and the current password.
public func getOtpStrings() -> (description: String, otp: String)? {
guard otpToken != nil else {
return nil
}
var description = otpType.description
if case let .timer(period) = otpToken!.generator.factor {
let timeSinceEpoch = Date().timeIntervalSince1970
let validTime = Int(period - timeSinceEpoch.truncatingRemainder(dividingBy: period))
description += " " + "ExpiresIn".localize(validTime)
}
return (description, otpToken!.currentPassword ?? "Error".localize())
}
// return the password strings
// it is guaranteed that it is a HOTP password when we call this
public func getNextHotp() -> String? {
// increase the counter
otpToken = otpToken?.updatedToken()
// replace old HOTP settings with the new otpauth
var newOtpauth = try! otpToken?.toURL().absoluteString
newOtpauth?.append("&secret=")
newOtpauth?.append(MF_Base32Codec.base32String(from: otpToken?.generator.secret))
var lines: [String] = []
plainText.enumerateLines { line, _ in
let (key, _) = Parser.getKeyValuePair(from: line)
if !Constants.OTP_KEYWORDS.contains(key ?? "") {
lines.append(line)
} else if key == Constants.OTPAUTH, newOtpauth != nil {
lines.append(newOtpauth!)
// set to nil to prevent duplication
newOtpauth = nil
}
}
if newOtpauth != nil {
lines.append(newOtpauth!)
}
updatePassword(name: name, path: path, plainText: lines.joined(separator: "\n"))
// get and return the password
return otpToken?.currentPassword
}
public func getUsernameForCompletion() -> String {
username ?? user ?? login ?? nameFromPath ?? ""
}
}