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

Add the ability to generate SSL certs from tray icon #778

Merged
merged 22 commits into from
Apr 21, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c611395
move `config.go` to it's own package and make functions public.
umbynos Mar 23, 2023
a5bfc94
move `config.ini` in the right package and remove hack
umbynos Mar 30, 2023
2ce9a06
fix linter
umbynos Mar 30, 2023
ac361f7
move `CrashesIsEmpty` function to the config package and rename it
umbynos Mar 23, 2023
02eacd1
move `certificate.go` in it's own package and make functions public
umbynos Mar 23, 2023
14dfc2b
update license header
umbynos Mar 31, 2023
f7d9772
add menu option to generate the certs only if they are not present
umbynos Mar 28, 2023
1971f9e
systray is useless in this func
umbynos Mar 28, 2023
e83c557
add cert install on macos
umbynos Mar 30, 2023
bcaeb75
add cert install on win
umbynos Apr 7, 2023
7f436f2
fix certificate not being valid for 127.0.0.1
umbynos Apr 6, 2023
3a5cb38
disable the generation/install certs menuItem on OS that are not macos
umbynos Apr 12, 2023
b62a2ff
remove the cert generation from the installer, remove duplicate step
umbynos Apr 14, 2023
2b41a4d
parallelization for notarization is no more required
umbynos Apr 14, 2023
d27ddb0
test new version of the installer config
umbynos Apr 14, 2023
3e7fead
move archive generation in the CI and save a rename operation (we do …
umbynos Apr 17, 2023
0b35ff4
removed `-` in arch matrix variable for clarity
umbynos Apr 17, 2023
b6f6947
Revert "add cert install on win"
umbynos Apr 19, 2023
8007107
add popup on error
umbynos Apr 20, 2023
4dde91e
Fixed warnings in obj-c code
cmaglie Apr 20, 2023
85a7b00
remove the certs if the install process errors. The user is able to r…
umbynos Apr 21, 2023
bda1574
Revert "test new version of the installer config"
umbynos Apr 17, 2023
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
35 changes: 25 additions & 10 deletions certificates.go → certificates/certificates.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2023 Arduino SA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// Generate a self-signed X.509 certificate for a TLS server. Outputs to
// 'cert.pem' and 'key.pem' and will overwrite existing files.

package main
package certificates

import (
"crypto/ecdsa"
Expand All @@ -23,6 +34,7 @@ import (
"text/template"
"time"

"github.com/arduino/arduino-create-agent/config"
"github.com/arduino/go-paths-helper"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -133,10 +145,10 @@ func generateSingleCertificate(isCa bool) (*x509.Certificate, error) {
return &template, nil
}

// migrateCertificatesGeneratedWithOldAgentVersions checks if certificates generated
// MigrateCertificatesGeneratedWithOldAgentVersions checks if certificates generated
// with an old version of the Agent needs to be migrated to the current certificates
// directory, and performs the migration if needed.
func migrateCertificatesGeneratedWithOldAgentVersions(certsDir *paths.Path) {
func MigrateCertificatesGeneratedWithOldAgentVersions(certsDir *paths.Path) {
if certsDir.Join("ca.cert.pem").Exist() {
// The new certificates are already set-up, nothing to do
return
Expand All @@ -160,7 +172,8 @@ func migrateCertificatesGeneratedWithOldAgentVersions(certsDir *paths.Path) {
}
}

func generateCertificates(certsDir *paths.Path) {
// GenerateCertificates will generate the required certificates useful for a HTTPS connection on localhost
func GenerateCertificates(certsDir *paths.Path) {
certsDir.Join("ca.cert.pem").Remove()
certsDir.Join("ca.key.pem").Remove()
certsDir.Join("cert.pem").Remove()
Expand Down Expand Up @@ -259,7 +272,8 @@ func generateCertificates(certsDir *paths.Path) {
}
}

func certHandler(c *gin.Context) {
// CertHandler will expone the certificate (we do not know why this was required)
func CertHandler(c *gin.Context) {
if strings.Contains(c.Request.UserAgent(), "Firefox") {
c.Header("content-type", "application/x-x509-ca-cert")
c.File("ca.cert.cer")
Expand All @@ -270,8 +284,9 @@ func certHandler(c *gin.Context) {
})
}

func deleteCertHandler(c *gin.Context) {
DeleteCertificates(getCertificatesDir())
// DeleteCertHandler will delete the certificates
func DeleteCertHandler(c *gin.Context) {
DeleteCertificates(config.GetCertificatesDir())
}

// DeleteCertificates will delete the certificates
Expand Down
69 changes: 69 additions & 0 deletions certificates/install_darwin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2023 Arduino SA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

package certificates

//inspired by https://stackoverflow.com/questions/12798950/ios-install-ssl-certificate-programmatically

/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#import <Cocoa/Cocoa.h>

void 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 ) {
NSLog(@"duplicate root certificate entry");
} else {
NSLog(@"install root certificate failure");
}

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

*/
import "C"
import (
log "github.com/sirupsen/logrus"

"github.com/arduino/go-paths-helper"
)

// InstallCertificate will install the certificates in the system keychain on macos
func InstallCertificate(cert *paths.Path) {
log.Infof("Installing certificate: %s", cert)
C.installCert(C.CString(cert.String()))
}
29 changes: 29 additions & 0 deletions certificates/install_default.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2023 Arduino SA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//go:build !darwin && !windows

package certificates

import (
log "github.com/sirupsen/logrus"

"github.com/arduino/go-paths-helper"
)

// InstallCertificate won't do anything on unsupported Operative Systems
func InstallCertificate(cert *paths.Path) {
log.Warn("platform not supported for the certificate install")
}
104 changes: 104 additions & 0 deletions certificates/install_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright 2023 Arduino SA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// code inspired by https://github.com/FiloSottile/mkcert licenced under BSD3

package certificates

import (
"encoding/pem"
"fmt"
"io/ioutil"
"syscall"
"unsafe"

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

var (
modcrypt32 = syscall.NewLazyDLL("crypt32.dll")
procCertAddEncodedCertificateToStore = modcrypt32.NewProc("CertAddEncodedCertificateToStore")
procCertCloseStore = modcrypt32.NewProc("CertCloseStore")
procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW")
)

// // InstallCertificate will install the certificates in the system keychain on windows
func InstallCertificate(certFile *paths.Path) {
// Load cert
cert, err := ioutil.ReadFile(certFile.String())
if err != nil {
log.Errorf("failed to read root certificate: %s", err)
}
// Decode PEM
if certBlock, _ := pem.Decode(cert); certBlock == nil || certBlock.Type != "CERTIFICATE" {
log.Error("invalid PEM data: decode pem")
} else {
cert = certBlock.Bytes
}
// Open root store
store, err := openWindowsRootStore()
if err != nil {
log.Errorf("cannot open root store %s", err)
umbynos marked this conversation as resolved.
Show resolved Hide resolved
} else {
log.Info("opened Root Store")
}
defer store.close()
// Add cert
err = store.addCert(cert)
if err != nil {
log.Errorf("cannot install certificate in the system keychain: %s", err)
} else {
log.Info("certificate installed")
}
}

type windowsRootStore uintptr

func openWindowsRootStore() (windowsRootStore, error) {
rootStr, err := syscall.UTF16PtrFromString("ROOT")
if err != nil {
return 0, err
}
store, _, err := procCertOpenSystemStoreW.Call(0, uintptr(unsafe.Pointer(rootStr)))
if store != 0 {
return windowsRootStore(store), nil
}
return 0, fmt.Errorf("failed to open windows root store: %s", err)
}

func (w windowsRootStore) close() error {
ret, _, err := procCertCloseStore.Call(uintptr(w), 0)
if ret != 0 {
return nil
}
return fmt.Errorf("failed to close windows root store: %s", err)
}

func (w windowsRootStore) addCert(cert []byte) error {
// this will always override
ret, _, err := procCertAddEncodedCertificateToStore.Call(
uintptr(w), // HCERTSTORE hCertStore
uintptr(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING), // DWORD dwCertEncodingType
uintptr(unsafe.Pointer(&cert[0])), // const BYTE *pbCertEncoded
uintptr(len(cert)), // DWORD cbCertEncoded
3, // DWORD dwAddDisposition (CERT_STORE_ADD_REPLACE_EXISTING is 3)
0, // PCCERT_CONTEXT *ppCertContext
)
if ret != 0 {
return nil
}
return fmt.Errorf("failed adding cert: %s", err)
}
38 changes: 25 additions & 13 deletions config.go → config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,30 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

package main
package config

import (
// we need this for the config ini in this package
_ "embed"
"os"

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

// getCertificatesDir return the directory where SSL certificates are saved
func getCertificatesDir() *paths.Path {
return getDataDir()
// GetCertificatesDir return the directory where SSL certificates are saved
func GetCertificatesDir() *paths.Path {
return GetDataDir()
}

// getDataDir returns the full path to the default Arduino Create Agent data directory.
func getDataDir() *paths.Path {
// CertsExist checks if the certs have already been generated
func CertsExist() bool {
certFile := GetCertificatesDir().Join("cert.pem")
return certFile.Exist() //if the certFile is not present we assume there are no certs
}

// GetDataDir returns the full path to the default Arduino Create Agent data directory.
func GetDataDir() *paths.Path {
userDir, err := os.UserHomeDir()
if err != nil {
log.Panicf("Could not get user dir: %s", err)
Expand All @@ -41,17 +48,22 @@ func getDataDir() *paths.Path {
return dataDir
}

// getLogsDir return the directory where logs are saved
func getLogsDir() *paths.Path {
logsDir := getDataDir().Join("logs")
// GetLogsDir return the directory where logs are saved
func GetLogsDir() *paths.Path {
logsDir := GetDataDir().Join("logs")
if err := logsDir.MkdirAll(); err != nil {
log.Panicf("Can't create logs dir: %s", err)
}
return logsDir
}

// getDefaultConfigDir returns the full path to the default Arduino Create Agent configuration directory.
func getDefaultConfigDir() *paths.Path {
// LogsIsEmpty checks if the folder containing crash-reports is empty
func LogsIsEmpty() bool {
return GetLogsDir().NotExist() // if the logs directory is empty we assume there are no crashreports
}

// GetDefaultConfigDir returns the full path to the default Arduino Create Agent configuration directory.
func GetDefaultConfigDir() *paths.Path {
// UserConfigDir returns the default root directory to use
// for user-specific configuration data. Users should create
// their own application-specific subdirectory within this
Expand Down Expand Up @@ -82,10 +94,10 @@ func getDefaultConfigDir() *paths.Path {
//go:embed config.ini
var configContent []byte

// generateConfig function will take a directory path as an input
// GenerateConfig function will take a directory path as an input
// and will write the default config,ini file to that directory,
// it will panic if something goes wrong
func generateConfig(destDir *paths.Path) *paths.Path {
func GenerateConfig(destDir *paths.Path) *paths.Path {
configPath := destDir.Join("config.ini")

// generate the config.ini file directly in destDir
Expand Down
File renamed without changes.
5 changes: 4 additions & 1 deletion hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ import (
"strconv"
"strings"

cert "github.com/arduino/arduino-create-agent/certificates"
"github.com/arduino/arduino-create-agent/config"

"github.com/arduino/arduino-create-agent/upload"
log "github.com/sirupsen/logrus"
)
Expand Down Expand Up @@ -182,7 +185,7 @@ func checkCmd(m []byte) {
} else if strings.HasPrefix(sl, "downloadtool") {
// Always delete root certificates when we receive a downloadtool command
// Useful if the install procedure was not followed strictly (eg. manually)
DeleteCertificates(getCertificatesDir())
cert.DeleteCertificates(config.GetCertificatesDir())
go func() {
args := strings.Split(s, " ")
var tool, toolVersion, pack, behaviour string
Expand Down
Loading