@@ -18,7 +18,9 @@ package certificates
1818//inspired by https://stackoverflow.com/questions/12798950/ios-install-ssl-certificate-programmatically
1919
2020/*
21+ // Explicitly tell the GCC compiler that the language is Objective-C.
2122#cgo CFLAGS: -x objective-c
23+ // Pass the list of macOS frameworks needed by this piece of Objective-C code.
2224#cgo LDFLAGS: -framework Cocoa
2325#import <Cocoa/Cocoa.h>
2426
@@ -61,6 +63,32 @@ const char *installCert(const char *path) {
6163 return "";
6264}
6365
66+ const char *uninstallCert() {
67+ // Each line is a key-value of the dictionary. Note: the the inverted order, value first then key.
68+ NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
69+ (id)kSecClassCertificate, kSecClass,
70+ CFSTR("Arduino"), kSecAttrLabel,
71+ kSecMatchLimitOne, kSecMatchLimit,
72+ kCFBooleanTrue, kSecReturnAttributes,
73+ nil];
74+
75+ OSStatus err = noErr;
76+ // Use this function to check for errors
77+ err = SecItemCopyMatching((CFDictionaryRef)dict, nil);
78+ if (err == noErr) {
79+ err = SecItemDelete((CFDictionaryRef)dict);
80+ if (err != noErr) {
81+ NSString *errString = [@"Could not delete the certificates. Error: " stringByAppendingFormat:@"%d", err];
82+ NSLog(@"%@", errString);
83+ return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];;
84+ }
85+ } else if (err != errSecItemNotFound){
86+ NSString *errString = [@"Error: " stringByAppendingFormat:@"%d", err];
87+ NSLog(@"%@", errString);
88+ return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];;
89+ }
90+ return "";
91+ }
6492*/
6593import "C"
6694import (
@@ -82,7 +110,22 @@ func InstallCertificate(cert *paths.Path) error {
82110 p := C .installCert (ccert )
83111 s := C .GoString (p )
84112 if len (s ) != 0 {
85- oscmd := exec .Command ("osascript" , "-e" , "display dialog \" " + s + "\" buttons \" OK\" with title \" Error installing certificates\" " )
113+ oscmd := exec .Command ("osascript" , "-e" , "display dialog \" " + s + "\" buttons \" OK\" with title \" Arduino Agent: Error installing certificates\" " )
114+ _ = oscmd .Run ()
115+ _ = UninstallCertificates ()
116+ return errors .New (s )
117+ }
118+ return nil
119+ }
120+
121+ // UninstallCertificates will uninstall the certificates from the system keychain on macos,
122+ // if something goes wrong will show a dialog with the error and return an error
123+ func UninstallCertificates () error {
124+ log .Infof ("Uninstalling certificates" )
125+ p := C .uninstallCert ()
126+ s := C .GoString (p )
127+ if len (s ) != 0 {
128+ oscmd := exec .Command ("osascript" , "-e" , "display dialog \" " + s + "\" buttons \" OK\" with title \" Arduino Agent: Error uninstalling certificates\" " )
86129 _ = oscmd .Run ()
87130 return errors .New (s )
88131 }
0 commit comments