Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix buttons and improve handling of certificates when Safari is not the default browser #949

Merged
merged 19 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
f43b0e4
Fix check on buttons returning the correct message
MatteoPologruto May 8, 2024
f69980a
Update certificates regardless of the default browser
MatteoPologruto May 8, 2024
f7bd6e3
Set installCerts when the certificate is installed from previous vers…
MatteoPologruto May 8, 2024
8006310
Do not set installCerts to false if the default browser is not Safari
MatteoPologruto May 8, 2024
aa02ed0
Do not ask again to update the certificate if the user refuses once
MatteoPologruto May 9, 2024
e46bfbf
Fix user script on macOS
MatteoPologruto May 9, 2024
7f4cdf6
Check for the presence of the certificate in the keychain to determin…
MatteoPologruto May 9, 2024
4285c04
Fix getExpirationDate breaking when the certificate is expired
MatteoPologruto May 9, 2024
4064541
Fix return value in case of error
MatteoPologruto May 9, 2024
cf31546
getExpirationDate rewritten to use the correct expiration field.
Xayton May 9, 2024
411d051
Separate osascript default button from the one to press
MatteoPologruto May 9, 2024
c11610b
Fix leftover buttons
MatteoPologruto May 9, 2024
9494f25
Small text fixes in the "manage certificate" dialog
Xayton May 10, 2024
d56f231
Simplify error management in getExpirationDate
Xayton May 10, 2024
8ec1efc
Fix compiler warnings and move obj-c code into a separate file.
Xayton May 10, 2024
34fae24
certInKeychain returns a bool
Xayton May 10, 2024
8854680
Fix building errors caused by objective-c files on Ubuntu and Windows
MatteoPologruto May 13, 2024
681a250
Build objective-c files only on Darwin
MatteoPologruto May 13, 2024
c461c40
Remove -ld_classic library because XCode is not up to date on the CI
MatteoPologruto May 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 3 additions & 31 deletions certificates/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,13 @@ import (
"math/big"
"net"
"os"
"strings"
"time"

"github.com/arduino/arduino-create-agent/utilities"
"github.com/arduino/go-paths-helper"
log "github.com/sirupsen/logrus"
)

var (
host = "localhost"
validFrom = ""
validFor = 365 * 24 * time.Hour * 2 // 2 years
rsaBits = 2048
Expand Down Expand Up @@ -270,41 +267,16 @@ func DeleteCertificates(certDir *paths.Path) {
certDir.Join("cert.cer").Remove()
}

// isExpired checks if a certificate is expired or about to expire (less than 1 month)
func isExpired() (bool, error) {
// IsExpired checks if a certificate is expired or about to expire (less than 1 month)
func IsExpired() (bool, error) {
bound := time.Now().AddDate(0, 1, 0)
dateS, err := GetExpirationDate()
date, err := GetExpirationDate()
if err != nil {
return false, err
}
date, _ := time.Parse(time.DateTime, dateS)
return date.Before(bound), nil
}

// PromptInstallCertsSafari prompts the user to install the HTTPS certificates if they are using Safari
func PromptInstallCertsSafari() bool {
buttonPressed := utilities.UserPrompt("display dialog \"The Arduino Agent needs a local HTTPS certificate to work correctly with Safari.\nIf you use Safari, you need to install it.\" buttons {\"Do not install\", \"Install the certificate for Safari\"} default button 2 with title \"Arduino Agent: Install certificate\"")
return strings.Contains(string(buttonPressed), "button returned:Install the certificate for Safari")
}

// PromptExpiredCerts prompts the user to update the HTTPS certificates if they are using Safari
func PromptExpiredCerts(certDir *paths.Path) {
if expired, err := isExpired(); err != nil {
log.Errorf("cannot check if certificates are expired something went wrong: %s", err)
} else if expired {
buttonPressed := utilities.UserPrompt("display dialog \"The Arduino Agent needs a local HTTPS certificate to work correctly with Safari.\nYour certificate is expired or close to expiration. Do you want to update it?\" buttons {\"Do not update\", \"Update the certificate for Safari\"} default button 2 with title \"Arduino Agent: Update certificate\"")
if strings.Contains(string(buttonPressed), "button returned:Update the certificate for Safari") {
err := UninstallCertificates()
if err != nil {
log.Errorf("cannot uninstall certificates something went wrong: %s", err)
} else {
DeleteCertificates(certDir)
GenerateAndInstallCertificates(certDir)
}
}
}
}

// GenerateAndInstallCertificates generates and installs the certificates
func GenerateAndInstallCertificates(certDir *paths.Path) {
GenerateCertificates(certDir)
Expand Down
7 changes: 7 additions & 0 deletions certificates/certificates_darwin.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const char *getDefaultBrowserName();

const char *installCert(const char *path);
const char *uninstallCert();
const bool certInKeychain();

const char *getExpirationDate(long *expirationDate);
137 changes: 137 additions & 0 deletions certificates/certificates_darwin.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#include "certificates_darwin.h"

// Used to return error strings (as NSString) as a C-string to the Go code.
const char *toErrorString(NSString *errString) {
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
}

// Returns a string describing the name of the default browser set for the user, nil in case of error.
const char *getDefaultBrowserName() {
NSURL *defaultBrowserURL = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:[NSURL URLWithString:@"http://"]];
if (defaultBrowserURL) {
NSBundle *defaultBrowserBundle = [NSBundle bundleWithURL:defaultBrowserURL];
NSString *defaultBrowser = [defaultBrowserBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];

return [defaultBrowser cStringUsingEncoding:[NSString defaultCStringEncoding]];
}

return "";
}

// inspired by https://stackoverflow.com/questions/12798950/ios-install-ssl-certificate-programmatically
const char *installCert(const char *path) {
NSURL *url = [NSURL fileURLWithPath:@(path) isDirectory:NO];
NSData *rootCertData = [NSData dataWithContentsOfURL:url];

OSStatus err = noErr;
SecCertificateRef rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) rootCertData);

CFTypeRef result;

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassCertificate, kSecClass,
rootCert, kSecValueRef,
nil];

err = SecItemAdd((CFDictionaryRef)dict, &result);

if (err == noErr) {
NSLog(@"Install root certificate success");
} else if (err == errSecDuplicateItem) {
NSString *errString = [@"duplicate root certificate entry. Error: " stringByAppendingFormat:@"%d", err];
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
} else {
NSString *errString = [@"install root certificate failure. Error: " stringByAppendingFormat:@"%d", err];
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
}

NSDictionary *newTrustSettings = @{(id)kSecTrustSettingsResult: [NSNumber numberWithInt:kSecTrustSettingsResultTrustRoot]};
err = SecTrustSettingsSetTrustSettings(rootCert, kSecTrustSettingsDomainUser, (__bridge CFTypeRef)(newTrustSettings));
if (err != errSecSuccess) {
NSString *errString = [@"Could not change the trust setting for a certificate. Error: " stringByAppendingFormat:@"%d", err];
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
}

return "";
}

const char *uninstallCert() {
// Each line is a key-value of the dictionary. Note: the the inverted order, value first then key.
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassCertificate, kSecClass,
CFSTR("Arduino"), kSecAttrLabel,
kSecMatchLimitOne, kSecMatchLimit,
kCFBooleanTrue, kSecReturnAttributes,
nil];

OSStatus err = noErr;
// Use this function to check for errors
err = SecItemCopyMatching((CFDictionaryRef)dict, nil);
if (err == noErr) {
err = SecItemDelete((CFDictionaryRef)dict);
if (err != noErr) {
NSString *errString = [@"Could not delete the certificates. Error: " stringByAppendingFormat:@"%d", err];
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
}
} else if (err != errSecItemNotFound){
NSString *errString = [@"Error: " stringByAppendingFormat:@"%d", err];
NSLog(@"%@", errString);
return [errString cStringUsingEncoding:[NSString defaultCStringEncoding]];
}
return "";
}

const bool certInKeychain() {
// Create a key-value dictionary used to query the Keychain and look for the "Arduino" root certificate.
NSDictionary *getquery = @{
(id)kSecClass: (id)kSecClassCertificate,
(id)kSecAttrLabel: @"Arduino",
(id)kSecReturnRef: @YES,
};

OSStatus err = SecItemCopyMatching((CFDictionaryRef)getquery, nil);
return (err == noErr); // No error means the certificate was found, otherwise err will be "errSecItemNotFound".
}

// Returns the expiration date "kSecOIDX509V1ValidityNotAfter" of the Arduino certificate.
// The value is returned as a CFAbsoluteTime: a long number of seconds from the date of 1 Jan 2001 00:00:00 GMT.
const char *getExpirationDate(long *expirationDate) {
// Create a key-value dictionary used to query the Keychain and look for the "Arduino" root certificate.
NSDictionary *getquery = @{
(id)kSecClass: (id)kSecClassCertificate,
(id)kSecAttrLabel: @"Arduino",
(id)kSecReturnRef: @YES,
};

SecCertificateRef cert = NULL;

// Search the keychain for certificates matching the query above.
OSStatus err = SecItemCopyMatching((CFDictionaryRef)getquery, (CFTypeRef *)&cert);
if (err != noErr) return toErrorString([@"Error getting the certificate: " stringByAppendingFormat:@"%d", err]);

// Get data from the certificate, as a dictionary of properties. We just need the "invalidity not after" property.
CFDictionaryRef certDict = SecCertificateCopyValues(cert,
(__bridge CFArrayRef)@[(__bridge id)kSecOIDX509V1ValidityNotAfter], NULL);
if (certDict == NULL) return toErrorString(@"SecCertificateCopyValues failed");


// Get the "validity not after" property as a dictionary, and get the "value" key (that is a number).
CFDictionaryRef validityNotAfterDict = CFDictionaryGetValue(certDict, kSecOIDX509V1ValidityNotAfter);
if (validityNotAfterDict == NULL) return toErrorString(@"CFDictionaryGetValue (validity) failed");

CFNumberRef number = (CFNumberRef)CFDictionaryGetValue(validityNotAfterDict, kSecPropertyKeyValue);
if (number == NULL) return toErrorString(@"CFDictionaryGetValue (keyValue) failed");

CFNumberGetValue(number, kCFNumberSInt64Type, expirationDate);
// NSLog(@"Certificate validity not after: %ld", *expirationDate);

CFRelease(certDict);
return ""; // No error.
}
Loading
Loading