This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
CertificateSelection.mm
284 lines (251 loc) · 11.4 KB
/
CertificateSelection.mm
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
* Chrome Token Signing Native Host
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#import "CertificateSelection.h"
#import "BinaryUtils.h"
#import "PKCS11CardManager.h"
#import "Labels.h"
#import "PKCS11Path.h"
#import "Logger.h"
#import <SecurityInterface/SFCertificatePanel.h>
#import <SecurityInterface/SFCertificateView.h>
#import <Security/Security.h>
#define _L(KEY) @(Labels::l10n.get(KEY).c_str())
static NSTouchBarItemIdentifier touchBarItemGroupId = @"ee.ria.chrome-token-signing.touchbar.group";
static NSTouchBarItemIdentifier touchBarItemSelectId = @"ee.ria.chrome-token-signing.touchbar.select";
static NSTouchBarItemIdentifier touchBarItemCancelId = @"ee.ria.chrome-token-signing.touchbar.cancel";
static NSTouchBarItemIdentifier touchBarItemSegmentId = @"ee.ria.chrome-token-signing.touchbar.segment";
@interface CertificateSelection () <NSTableViewDataSource,NSTableViewDelegate,NSTouchBarDelegate> {
IBOutlet NSPanel *window;
IBOutlet NSTableView *certificateSelection;
IBOutlet NSButton *okButton;
IBOutlet NSButton *cancelButton;
IBOutlet NSTextField *warningLabel;
NSMutableArray *certificates;
}
@end
@implementation CertificateSelection
- (bool)isDuplicate:(NSString*)certificate {
for (NSDictionary *cert in certificates) {
if ([cert[@"cert"] isEqualToString:certificate])
return true;
}
return false;
}
- (instancetype)init:(bool)forSigning
{
if (self = [super init]) {
certificates = [[NSMutableArray alloc] init];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"dd.MM.YYYY";
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 2001;
PKCS11Path::Params p11 = PKCS11Path::getPkcs11ModulePath();
for (const PKCS11CardManager::Token &token : PKCS11CardManager(p11.path).tokens()) {
CFDataRef data = CFDataCreateWithBytesNoCopy(nil, token.cert.data(), token.cert.size(), kCFAllocatorNull);
SecCertificateRef cert = SecCertificateCreateWithData(nil, data);
CFRelease(data);
NSDictionary *dict = CFBridgingRelease(SecCertificateCopyValues(cert, nil, nil));
CFRelease(cert);
NSNumber *ku = dict[(__bridge NSString*)kSecOIDKeyUsage][(__bridge NSString*)kSecPropertyKeyValue];
const bool isNonRepudiation = ku.unsignedIntValue & kSecKeyUsageNonRepudiation;
if (forSigning != isNonRepudiation) {
_log("certificate is non-repu: %u, requesting signing certificate %u, moving on to next token...", isNonRepudiation, forSigning);
continue;
}
NSNumber *na = dict[(__bridge NSString*)kSecOIDX509V1ValidityNotAfter][(__bridge NSString*)kSecPropertyKeyValue];
NSDate *date = [NSDate dateWithTimeInterval:na.intValue sinceDate:[NSCalendar.currentCalendar dateFromComponents:components]];
NSString *hex = @(BinaryUtils::bin2hex(token.cert).c_str());
if ([date compare:NSDate.date] <= 0 || [self isDuplicate:hex]) {
_log("token has expired or is duplicate");
continue;
}
_log("token has valid signing certificate, adding it to selection");
NSString *cn = [NSString string];
NSString *type = [NSString string];
for (NSDictionary *item in dict[(__bridge NSString*)kSecOIDX509V1SubjectName][(__bridge NSString*)kSecPropertyKeyValue]) {
if ([item[(__bridge NSString*)kSecPropertyKeyLabel] isEqualToString:(__bridge NSString*)kSecOIDCommonName]) {
cn = item[(__bridge NSString*)kSecPropertyKeyValue];
}
if ([item[(__bridge NSString*)kSecPropertyKeyLabel] isEqualToString:(__bridge NSString*)kSecOIDOrganizationName]) {
type = item[(__bridge NSString*)kSecPropertyKeyValue];
}
}
[certificates addObject: @{@"cert": hex, @"validTo": [df stringFromDate:date], @"CN": cn, @"type": type}];
}
if (![[NSBundle bundleForClass:CertificateSelection.class] loadNibNamed:@"CertificateSelection" owner:self topLevelObjects:nil]) {
self = nil;
return self;
}
if (@available(macOS 10_12_2, *)) {
window.touchBar = [self makeTouchBar];
}
window.title = _L("select certificate");
cancelButton.title = _L("cancel");
okButton.title = _L("select");
warningLabel.stringValue = _L("cert info");
[[certificateSelection tableColumnWithIdentifier:@"CN"].headerCell setStringValue:_L("certificate")];
[[certificateSelection tableColumnWithIdentifier:@"type"].headerCell setStringValue:_L("type")];
[[certificateSelection tableColumnWithIdentifier:@"validTo"].headerCell setStringValue:_L("valid to")];
if (certificateSelection.numberOfRows > 0) {
[certificateSelection selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:FALSE];
okButton.enabled = YES;
}
}
return self;
}
+ (NSDictionary *)show:(bool)forSigning
{
try {
CertificateSelection *dialog = [[CertificateSelection alloc] init:forSigning];
if (!dialog) {
return @{@"result": @"technical_error"};
}
if (dialog->certificates.count == 0) {
return @{@"result": @"no_certificates"};
}
[NSApp activateIgnoringOtherApps:YES];
NSModalResponse result = [NSApp runModalForWindow:dialog->window];
[dialog->window close];
if (result == NSModalResponseAbort || dialog->certificateSelection.selectedRow == -1) {
return @{@"result": @"user_cancel"};
}
return @{@"cert": dialog->certificates[dialog->certificateSelection.selectedRow][@"cert"]};
} catch(const BaseException &e) {
_log("Exception: %s", e.what());
return @{@"result": @(e.getErrorCode().c_str())};
}
}
- (void)showCertificate
{
NSString *hex = certificates[certificateSelection.selectedRow][@"cert"];
std::vector<unsigned char> der = BinaryUtils::hex2bin(hex.UTF8String);
CFDataRef data = CFDataCreateWithBytesNoCopy(nil, der.data(), der.size(), kCFAllocatorNull);
id cert = CFBridgingRelease(SecCertificateCreateWithData(nil, data));
CFRelease(data);
SFCertificatePanel *panel = [[SFCertificatePanel alloc] init];
[panel beginSheetForWindow:window modalDelegate:nil didEndSelector:nil contextInfo:nil certificates:@[cert] showGroup:NO];
}
- (IBAction)okClicked:(id)sender
{
[NSApp stopModal];
}
- (IBAction)cancelClicked:(id)sender
{
[NSApp abortModal];
}
- (IBAction)enableOkButton:(id)sender
{
okButton.enabled = certificateSelection.selectedRow != -1;
}
- (IBAction)changeSelection:(id)sender
{
NSUInteger index = certificateSelection.selectedRow >= 0 ? certificateSelection.selectedRow : 0;
switch ([sender selectedSegment]) {
case 0:
if (index > 0)
[certificateSelection selectRowIndexes:[NSIndexSet indexSetWithIndex:--index] byExtendingSelection:NO];
break;
case 1:
if (index < certificates.count -1)
[certificateSelection selectRowIndexes:[NSIndexSet indexSetWithIndex:++index] byExtendingSelection:NO];
break;
default:
[self showCertificate];
break;
}
}
#pragma mark - NSTouchBarProvider
- (NSTouchBar *)makeTouchBar NS_AVAILABLE_MAC(10_12_2)
{
NSTouchBar *touchBar = [[NSTouchBar alloc] init];
touchBar.delegate = self;
touchBar.defaultItemIdentifiers = @[NSTouchBarItemIdentifierFlexibleSpace, touchBarItemSegmentId, touchBarItemGroupId];
touchBar.principalItemIdentifier = touchBarItemGroupId;
return touchBar;
}
#pragma mark - NSTouchBarDelegate
- (NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier NS_AVAILABLE_MAC(10_12_2)
{
if ([identifier isEqualToString:touchBarItemGroupId])
{
NSArray *items = @[[self touchBar:touchBar makeItemForIdentifier:touchBarItemCancelId],
[self touchBar:touchBar makeItemForIdentifier:touchBarItemSelectId]];
return [NSGroupTouchBarItem groupItemWithIdentifier:identifier items:items];
}
if ([identifier isEqualToString:touchBarItemSegmentId])
{
NSSegmentedControl *control = [NSSegmentedControl segmentedControlWithImages:
@[[NSImage imageNamed:NSImageNameTouchBarGoUpTemplate], [NSImage imageNamed:NSImageNameTouchBarGoDownTemplate], [NSImage imageNamed:NSImageNameTouchBarGetInfoTemplate]]
trackingMode:NSSegmentSwitchTrackingMomentary target:self action:@selector(changeSelection:)];
NSCustomTouchBarItem *touchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
touchBarItem.view = control;
return touchBarItem;
}
if ([identifier isEqualToString:touchBarItemSelectId])
{
NSButton *button = [NSButton buttonWithTitle:_L("select") target:self action:@selector(okClicked:)];
button.bezelColor = NSColor.selectedMenuItemColor;
NSCustomTouchBarItem *touchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
touchBarItem.view = button;
return touchBarItem;
}
if ([identifier isEqualToString:touchBarItemCancelId])
{
NSCustomTouchBarItem *touchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
touchBarItem.view = [NSButton buttonWithTitle:_L("cancel") target:self action:@selector(cancelClicked:)];
return touchBarItem;
}
return nil;
}
#pragma mark - NSTableViewDataSource
- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView
{
return certificates.count;
}
- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row
{
if (certificates.count == 0) {
return [NSString string];
}
if ([tableColumn.identifier isEqualToString:@"CN"]) {
return certificates[row][@"CN"];
}
if ([tableColumn.identifier isEqualToString:@"type"]) {
return certificates[row][@"type"];
}
if ([tableColumn.identifier isEqualToString:@"validTo"]) {
return certificates[row][@"validTo"];
}
return [NSString string];
}
#pragma mark - NSTableViewDelegate
- (BOOL)tableView:(NSTableView*)tableView shouldSelectRow:(NSInteger)row
{
return okButton.enabled = YES;
}
- (BOOL)tableView:(NSTableView*)tableView shouldTypeSelectForEvent:(NSEvent*)event withCurrentSearchString:(NSString*)searchString
{
switch ([event.charactersIgnoringModifiers characterAtIndex:0]) {
case 0x20:
case 0x49:
[self showCertificate];
return NO;
default: return YES;
}
}
@end