forked from hrantzsch/keychain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keychain_mac.cpp
230 lines (190 loc) · 7.14 KB
/
keychain_mac.cpp
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
230
/*
* Copyright (c) 2013 GitHub Inc.
* Copyright (c) 2019 Hannes Rantzsch
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <vector>
#include <Security/Security.h>
#include "keychain.h"
namespace {
const SecKeychainRef defaultUserKeychain = NULL; // NULL means 'default'
/*! \brief Converts a CFString to a std::string
*
* This either uses CFStringGetCStringPtr or (if that fails) CFStringGetCString.
*/
std::string CFStringToStdString(const CFStringRef cfstring) {
const char *ccstr = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);
if (ccstr != nullptr) {
return std::string(ccstr);
}
auto utf16Pairs = CFStringGetLength(cfstring);
auto maxUtf8Bytes =
CFStringGetMaximumSizeForEncoding(utf16Pairs, kCFStringEncodingUTF8);
std::vector<char> cstr(maxUtf8Bytes, '\0');
auto result = CFStringGetCString(
cfstring, cstr.data(), cstr.size(), kCFStringEncodingUTF8);
return result ? std::string(cstr.data()) : std::string();
}
//! \brief Extracts a human readable string from a status code
std::string errorStatusToString(OSStatus status) {
const auto errorMessage = SecCopyErrorMessageString(status, NULL);
std::string errorString;
if (errorMessage) {
errorString = CFStringToStdString(errorMessage);
CFRelease(errorMessage);
}
return errorString;
}
std::string makeServiceName(const std::string &package,
const std::string &service) {
return package + "." + service;
}
/*! \brief Update error information
*
* If status indicates an error condition, set message, code and error type.
* Otherwise, set err to success.
*/
void updateError(keychain::Error &err, OSStatus status) {
if (status == errSecSuccess) {
err = keychain::Error{};
return;
}
err.message = errorStatusToString(status);
err.code = status;
switch (status) {
case errSecItemNotFound:
err.type = keychain::ErrorType::NotFound;
break;
// potential errors in case the user needs to unlock the keychain first
case errSecUserCanceled: // user pressed the Cancel button
case errSecAuthFailed: // too many failed password attempts
case errSecInteractionRequired: // user interaction required but not allowed
err.type = keychain::ErrorType::AccessDenied;
break;
default:
err.type = keychain::ErrorType::GenericError;
}
}
/*! \brief Modify an existing password
*
* Helper function that tries to find an existing password in the keychain and
* modifies it.
*/
OSStatus modifyPassword(const std::string &serviceName, const std::string &user,
const std::string &password) {
SecKeychainItemRef item = NULL;
OSStatus status = SecKeychainFindGenericPassword(
defaultUserKeychain,
static_cast<UInt32>(serviceName.length()),
serviceName.data(),
static_cast<UInt32>(user.length()),
user.data(),
NULL, // unused output parameter
NULL, // unused output parameter
&item);
if (status == errSecSuccess) {
status =
SecKeychainItemModifyContent(item,
NULL,
static_cast<UInt32>(password.length()),
password.data());
}
if (item) {
CFRelease(item);
}
return status;
}
} // namespace
namespace keychain {
void setPassword(const std::string &package, const std::string &service,
const std::string &user, const std::string &password,
Error &err) {
err = Error{};
const auto serviceName = makeServiceName(package, service);
OSStatus status =
SecKeychainAddGenericPassword(defaultUserKeychain,
static_cast<UInt32>(serviceName.length()),
serviceName.data(),
static_cast<UInt32>(user.length()),
user.data(),
static_cast<UInt32>(password.length()),
password.data(),
NULL /* unused output parameter */);
if (status == errSecDuplicateItem) {
// password exists -- override
status = modifyPassword(serviceName, user, password);
}
if (status != errSecSuccess) {
updateError(err, status);
}
}
std::string getPassword(const std::string &package, const std::string &service,
const std::string &user, Error &err) {
err = Error{};
const auto serviceName = makeServiceName(package, service);
void *data;
UInt32 length;
OSStatus status = SecKeychainFindGenericPassword(
defaultUserKeychain,
static_cast<UInt32>(serviceName.length()),
serviceName.data(),
static_cast<UInt32>(user.length()),
user.data(),
&length,
&data,
NULL /* unused output parameter */);
std::string password;
if (status != errSecSuccess) {
updateError(err, status);
} else if (data != NULL) {
password = std::string(reinterpret_cast<const char *>(data), length);
SecKeychainItemFreeContent(NULL, data);
}
return password;
}
void deletePassword(const std::string &package, const std::string &service,
const std::string &user, Error &err) {
err = Error{};
const auto serviceName = makeServiceName(package, service);
SecKeychainItemRef item;
OSStatus status = SecKeychainFindGenericPassword(
defaultUserKeychain,
static_cast<UInt32>(serviceName.length()),
serviceName.data(),
static_cast<UInt32>(user.length()),
user.data(),
NULL, // unused output parameter
NULL, // unused output parameter
&item);
if (status != errSecSuccess) {
updateError(err, status);
} else {
status = SecKeychainItemDelete(item);
if (status != errSecSuccess) {
updateError(err, status);
}
}
if (!err && item) {
CFRelease(item);
}
}
} // namespace keychain