33#include <nlohmann/json.hpp>
40#include <wx/filename.h>
56std::vector<wxString> splitArgs(
const wxString& aText )
58 std::vector<wxString> args;
63 for( wxUniChar c : aText )
66 if( !quoted && !inArg && c ==
'#' )
74 else if( !quoted && ( c ==
' ' || c ==
'\t' ) )
77 args.push_back( current );
90 args.push_back( current );
97std::vector<wxString> splitShellArgs(
const wxString& aText )
99 std::vector<wxString> args;
103 for(
auto it = aText.begin(); it != aText.end(); ++it )
105 const wxUniChar c = *it;
111 while( ++it != aText.end() && *it !=
'\'' )
114 if( it == aText.end() )
121 while( ++it != aText.end() && *it !=
'"' )
123 auto next = std::next( it );
125 if( *it ==
'\\' &&
next != aText.end()
134 if( it == aText.end() )
141 if( ++it == aText.end() )
146 else if( c ==
' ' || c ==
'\t' || c ==
'\n' )
149 args.push_back( current );
162 args.push_back( current );
169void splitKeyword(
const wxString& aLine, wxString& aKeyword, wxString& aArgs )
171 size_t end = aLine.find_first_of( wxS(
" \t=" ) );
173 if(
end == wxString::npos )
180 aKeyword = aLine.substr( 0,
end );
182 size_t start = aLine.find_first_not_of( wxS(
" \t" ),
end );
184 if( start != wxString::npos && aLine[start] ==
'=' )
185 start = aLine.find_first_not_of( wxS(
" \t" ), start + 1 );
187 aArgs = start == wxString::npos ? wxString() : aLine.substr( start );
193bool hostMatches(
const std::vector<wxString>& aPatterns,
const wxString& aHost )
195 bool matched =
false;
197 for(
const wxString& pattern : aPatterns )
199 const bool negated = pattern.StartsWith( wxS(
"!" ) );
200 wxString glob = negated ? pattern.Mid( 1 ) : pattern;
202 if( !aHost.Matches( glob ) )
215wxString expandPath(
const wxString& aValue,
const wxString& aHomeDir )
218 for(
size_t pos = aValue.find(
'%' ); pos != wxString::npos; pos = aValue.find(
'%', pos + 2 ) )
220 if( pos + 1 >= aValue.size() || aValue[pos + 1] !=
'd' )
225 wxString tail = aValue;
228 if( aValue == wxS(
"~" ) || aValue.StartsWith( wxS(
"~/" ) ) || aValue.StartsWith( wxS(
"~\\" ) ) )
231 tail = aValue.Mid( 1 );
234 tail.Replace( wxS(
"%d" ), aHomeDir );
241constexpr size_t MAX_DISCOVERED_KEYS = 4;
244struct DERIVED_PUBLIC_KEYS
251DERIVED_PUBLIC_KEYS& derivedPublicKeys()
253 static DERIVED_PUBLIC_KEYS store;
259wxString derivedPublicKeyPath(
const wxString& aKey )
264 DERIVED_PUBLIC_KEYS& store = derivedPublicKeys();
265 std::lock_guard<std::mutex> lock( store.mutex );
266 folder = store.folder;
269 if( folder.IsEmpty() || aKey.IsEmpty() )
270 return wxEmptyString;
272 uint64_t hash = 14695981039346656037ULL;
274 for(
unsigned char c : wxFileName( aKey ).GetFullPath().utf8_string() )
277 hash *= 1099511628211ULL;
280 return wxFileName( folder, wxString::Format( wxS(
"%016llx.pub" ),
static_cast<unsigned long long>( hash ) ) )
285uint32_t readUint32(
const unsigned char* aData )
287 return (
static_cast<uint32_t
>( aData[0] ) << 24 ) | (
static_cast<uint32_t
>( aData[1] ) << 16 )
288 | (
static_cast<uint32_t
>( aData[2] ) << 8 ) |
static_cast<uint32_t
>( aData[3] );
294std::string openSSHPublicKeyLine(
const std::string& aKeyText )
296 const std::string begin =
"-----BEGIN OPENSSH PRIVATE KEY-----";
297 size_t start = aKeyText.find( begin );
299 if( start == std::string::npos )
302 start += begin.size();
303 size_t end = aKeyText.find(
"-----END", start );
305 if(
end == std::string::npos )
308 wxMemoryBuffer raw = wxBase64Decode( aKeyText.data() + start,
end - start, wxBase64DecodeMode_SkipWS );
310 const unsigned char* data =
static_cast<const unsigned char*
>( raw.GetData() );
311 const size_t size = raw.GetDataLen();
312 const char magic[] =
"openssh-key-v1";
313 size_t pos =
sizeof( magic );
315 if( size < pos || std::memcmp( data, magic, pos ) != 0 )
319 for(
int field = 0; field < 3; ++field )
321 if( size < pos + 4 || size - pos - 4 < readUint32( data + pos ) )
324 pos += 4 + readUint32( data + pos );
327 if( size < pos + 8 || readUint32( data + pos ) == 0 )
330 const uint32_t blobLen = readUint32( data + pos + 4 );
333 if( size - pos < blobLen || blobLen < 4 || blobLen - 4 < readUint32( data + pos ) )
336 const std::string type(
reinterpret_cast<const char*
>( data + pos + 4 ), readUint32( data + pos ) );
341 return type +
" " + wxBase64Encode( data + pos, blobLen ).utf8_string() +
"\n";
346std::vector<wxString> scanSSHFolder(
const wxString& aSSHDir )
348 std::vector<wxString> keys;
351 if( !wxDir::Exists( aSSHDir ) || !dir.Open( aSSHDir ) )
356 for(
bool more = dir.GetFirst( &
name, wxEmptyString, wxDIR_FILES ); more; more = dir.GetNext( &
name ) )
358 const wxString
path = wxFileName( aSSHDir,
name ).GetFullPath();
360 if(
name.EndsWith( wxS(
".pub" ) ) || !wxFileName::FileExists(
path + wxS(
".pub" ) ) )
363 wxFFile file(
path, wxS(
"rb" ) );
365 size_t read = file.IsOpened() ? file.Read( head,
sizeof( head ) - 1 ) : 0;
367 if( std::string( head, read ).
find(
"PRIVATE KEY" ) != std::string::npos )
368 keys.push_back(
path );
371 std::sort( keys.begin(), keys.end() );
376struct REMEMBERED_KEYS
381 std::map<wxString, wxString> keys;
382 std::map<wxString, wxString> pending;
386REMEMBERED_KEYS& rememberedKeys()
388 static REMEMBERED_KEYS store;
393std::map<wxString, wxString> readRememberedKeys(
const wxString& aPath )
395 std::map<wxString, wxString> keys;
397 if( aPath.IsEmpty() )
400 std::ifstream file( aPath.fn_str(), std::ios::binary );
406 nlohmann::json
json = nlohmann::json::parse( file,
nullptr,
false );
408 if( !
json.is_object() )
411 for(
const auto& [remote, key] :
json.items() )
413 if( key.is_string() )
414 keys[wxString::FromUTF8( remote )] = wxString::FromUTF8( key.get<std::string>() );
421bool writeRememberedKeys(
const wxString& aPath,
const std::map<wxString, wxString>& aKeys )
423 nlohmann::json
json = nlohmann::json::object();
425 for(
const auto& [remote, key] : aKeys )
426 json[remote.utf8_string()] = key.utf8_string();
428 wxFileName fn( aPath );
430 if( !fn.DirExists() && !fn.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
434 wxTempFile out( aPath );
436 return out.IsOpened() && out.Write( wxString::FromUTF8(
json.dump( 2 ) ), wxConvUTF8 ) && out.Commit();
441void loadRememberedKeys( REMEMBERED_KEYS& aStore )
446 aStore.loaded =
true;
447 aStore.keys = readRememberedKeys( aStore.path );
454 const wxString& aHomeDir )
456 std::vector<wxString> files;
461 for( wxString line : wxSplit( aConfigText,
'\n',
'\0' ) )
463 line.Trim(
true ).Trim(
false );
465 if( line.IsEmpty() || line.StartsWith( wxS(
"#" ) ) )
470 splitKeyword( line, keyword, args );
473 if( keyword == wxS(
"host" ) )
475 active = hostMatches( splitArgs( args ), aHost );
477 else if( keyword == wxS(
"match" ) )
482 else if( active && keyword == wxS(
"identityfile" ) )
484 std::vector<wxString> values = splitArgs( args );
486 if( !values.empty() )
487 files.push_back( expandPath( values.front(), aHomeDir ) );
497 std::vector<wxString> files;
498 std::vector<wxString> args = splitShellArgs( aCommand );
500 for(
size_t ii = 0; ii < args.size(); ++ii )
502 if( args[ii] == wxS(
"-i" ) && ii + 1 < args.size() )
503 files.push_back( expandPath( args[++ii], aHomeDir ) );
504 else if( args[ii].StartsWith( wxS(
"-i" ) ) && args[ii].size() > 2 )
505 files.push_back( expandPath( args[ii].Mid( 2 ), aHomeDir ) );
513 const wxString& aSSHCommand )
515 std::vector<wxString> keys;
518 if( aHomeDir.IsEmpty() )
521 wxFileName sshDir( aHomeDir, wxEmptyString );
522 sshDir.AppendDir( wxS(
".ssh" ) );
524 const wxString configPath = wxFileName( sshDir.GetPath(), wxS(
"config" ) ).GetFullPath();
526 std::ifstream
config( configPath.fn_str(), std::ios::binary );
530 std::string
text( ( std::istreambuf_iterator<char>(
config ) ), std::istreambuf_iterator<char>() );
533 if(
text.rfind(
"\xEF\xBB\xBF", 0 ) == 0 )
546 for(
const wxString
name : { wxS(
"id_ed25519" ), wxS(
"id_ecdsa" ), wxS(
"id_rsa" ), wxS(
"id_dsa" ) } )
547 candidates.push_back( wxFileName( sshDir.GetPath(),
name ).GetFullPath() );
549 auto isKnown = [&](
const wxString& aPath )
551 return std::any_of( keys.begin(), keys.end(),
552 [&](
const wxString& aKey )
554 return IsSameSSHKey( aKey, aPath );
560 wxFileName fn( candidate );
563 if( !fn.IsAbsolute() || !wxFileName::FileExists( fn.GetFullPath() ) )
566 const wxString
path = fn.GetFullPath();
569 keys.push_back(
path );
572 for(
const wxString&
path : scanSSHFolder( sshDir.GetPath() ) )
574 if( keys.size() >= MAX_DISCOVERED_KEYS )
577 if( !isKnown(
path ) )
578 keys.push_back(
path );
587 if( aKey.IsEmpty() || aOther.IsEmpty() )
588 return aKey == aOther;
590 return wxFileName( aKey ).GetFullPath().IsSameAs( wxFileName( aOther ).GetFullPath(),
591 wxFileName::IsCaseSensitive() );
598 std::vector<wxString> homes;
605 homes.push_back( wxGetHomeDir() );
608 if( wxGetEnv( wxS(
"HOMEDRIVE" ), &drive ) && wxGetEnv( wxS(
"HOMEPATH" ), &
path ) && !drive.IsEmpty() )
609 homes.push_back( drive +
path );
611 if( wxGetEnv( wxS(
"USERPROFILE" ), &profile ) && !profile.IsEmpty() )
612 homes.push_back( profile );
614 if(
const char* home = std::getenv(
"HOME" ); home && *home )
616 homes.emplace_back( home, wxConvLibc );
621 passwd* found =
nullptr;
622 std::vector<char> buffer( 1024 );
625 while( ( rc = getpwuid_r( getuid(), &entry, buffer.data(), buffer.size(), &found ) ) == ERANGE )
626 buffer.resize( buffer.size() * 2 );
628 if( rc == 0 && found && found->pw_dir )
629 homes.emplace_back( found->pw_dir, wxConvLibc );
641 for(
const wxString& home : homes )
643 wxFileName sshDir( home, wxEmptyString );
644 sshDir.AppendDir( wxS(
".ssh" ) );
646 if( sshDir.DirExists() )
650 return homes.empty() ? wxString() : homes.front();
656 const wxString home =
HomeDir();
659 return wxEmptyString;
661 wxFileName sshDir( home, wxEmptyString );
662 sshDir.AppendDir( wxS(
".ssh" ) );
663 return sshDir.GetPath();
669 return aPicked.ends_with( wxS(
".pub" ) ) ? aPicked.Left( aPicked.size() - 4 ) : aPicked;
678 if( !file.IsOpened() || !file.ReadAll( &
text ) )
682 wxArrayString fields = wxSplit(
text.BeforeFirst(
'\n' ).Trim().Trim(
false ),
' ',
'\0' );
684 if( fields.size() < 2 )
687 wxMemoryBuffer blob = wxBase64Decode( fields[1] );
689 return std::string(
static_cast<const char*
>( blob.GetData() ), blob.GetDataLen() );
695 return !aKey.IsEmpty() && wxFileName::FileExists( aKey ) && !
EnsurePublicKeyFile( aKey ).IsEmpty();
702 return wxEmptyString;
704 if( wxFileName::FileExists( aKey + wxS(
".pub" ) ) )
705 return aKey + wxS(
".pub" );
707 const wxString derived = derivedPublicKeyPath( aKey );
709 return !derived.IsEmpty() && wxFileName::FileExists( derived ) ? derived : wxString();
715 if( aKey.IsEmpty() || wxFileName::FileExists( aKey + wxS(
".pub" ) ) )
718 const wxString derived = derivedPublicKeyPath( aKey );
719 std::ifstream file( aKey.fn_str(), std::ios::binary );
721 if( derived.IsEmpty() || !file )
722 return wxEmptyString;
724 const std::string line = openSSHPublicKeyLine(
725 std::string( ( std::istreambuf_iterator<char>( file ) ), std::istreambuf_iterator<char>() ) );
728 return wxEmptyString;
731 std::ifstream old( derived.fn_str(), std::ios::binary );
732 const std::string current( ( std::istreambuf_iterator<char>( old ) ), std::istreambuf_iterator<char>() );
734 if( current == line )
737 wxFileName fn( derived );
739 if( !fn.DirExists() && !fn.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
740 return wxEmptyString;
742 wxTempFile out( derived );
744 if( out.IsOpened() && out.Write( wxString::FromUTF8( line ), wxConvUTF8 ) && out.Commit() )
747 wxLogTrace(
traceGit,
"Could not write the public key for %s to %s", aKey, derived );
748 return wxEmptyString;
754 DERIVED_PUBLIC_KEYS& store = derivedPublicKeys();
755 std::lock_guard<std::mutex> lock( store.mutex );
762 REMEMBERED_KEYS& store = rememberedKeys();
763 std::lock_guard<std::mutex> lock( store.mutex );
764 loadRememberedKeys( store );
766 auto it = store.keys.find( aRemote );
767 return it == store.keys.end() ? wxString() : it->second;
773 if( aRemote.IsEmpty() || aKey.IsEmpty() )
776 REMEMBERED_KEYS& store = rememberedKeys();
777 std::lock_guard<std::mutex> lock( store.mutex );
778 loadRememberedKeys( store );
780 auto it = store.keys.find( aRemote );
782 if( it != store.keys.end() &&
IsSameSSHKey( it->second, aKey ) && store.pending.empty() )
785 store.keys[aRemote] = aKey;
786 store.pending[aRemote] = aKey;
788 if( store.path.IsEmpty() )
792 std::map<wxString, wxString> merged = readRememberedKeys( store.path );
794 for(
const auto& [remote, key] : store.pending )
795 merged[remote] = key;
797 if( writeRememberedKeys( store.path, merged ) )
799 store.keys = std::move( merged );
800 store.pending.clear();
804 wxLogTrace(
traceGit,
"Could not save remembered SSH keys to %s", store.path );
811 REMEMBERED_KEYS& store = rememberedKeys();
812 std::lock_guard<std::mutex> lock( store.mutex );
814 store.loaded =
false;
816 store.pending.clear();
const wxChar *const traceGit
Flag to enable Git debugging output.
APIEXPORT wxString PrivateKeyPath(const wxString &aPicked)
The private key for a path picked in a file dialog, which may be the key's .pub file.
APIEXPORT bool IsOfferableSSHKey(const wxString &aKey)
Whether aKey can be offered to a server.
APIEXPORT wxString EnsurePublicKeyFile(const wxString &aKey)
PublicKeyPath for aKey, first writing a public key file to KiCad's cache when the key has no ....
APIEXPORT wxString RememberedSSHKey(const wxString &aRemote)
The key that last connected to aRemote, or empty.
APIEXPORT std::vector< wxString > ParseSSHCommandIdentityFiles(const wxString &aCommand, const wxString &aHomeDir)
The -i key files in an ssh command line such as git's core.sshCommand, in order.
APIEXPORT std::vector< wxString > ParseSSHConfigIdentityFiles(const wxString &aConfigText, const wxString &aHost, const wxString &aHomeDir)
The IdentityFile entries an ssh config gives aHost, in file order.
APIEXPORT wxString PublicKeyPath(const wxString &aKey)
The public key file to offer with aKey.
APIEXPORT void SetDerivedPublicKeyFolder(const wxString &aDir)
Keep public key files written by EnsurePublicKeyFile in aDir.
APIEXPORT std::vector< wxString > DefaultSSHKeyCandidates(const wxString &aHomeDir, const wxString &aHost, const wxString &aSSHCommand=wxEmptyString)
Private keys to offer aHost, best first.
APIEXPORT wxString HomeDir()
The user's home folder, where ssh looks for its config and default keys: the first candidate with a ....
APIEXPORT wxString SSHKeyFolder()
The folder ssh keeps keys in, for a file picker to open at. Empty when the home folder is unknown.
APIEXPORT void RememberSSHKey(const wxString &aRemote, const wxString &aKey)
Remember aKey as the key that connected to aRemote. Safe to call from any thread.
APIEXPORT std::vector< wxString > HomeDirCandidates()
The folders that may be the user's home, most likely first.
APIEXPORT void SetRememberedSSHKeyStore(const wxString &aPath)
Keep remembered keys in aPath.
APIEXPORT std::string PublicKeyBlob(const wxString &aKey)
The public key blob from aKey's public key file, as the server sees it, or empty when it cannot be re...
APIEXPORT bool IsSameSSHKey(const wxString &aKey, const wxString &aOther)
Whether two key paths name the same file.
static std::string decoded(const std::string &aBase64)
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
wxLogTrace helper definitions.