From 7e23a11e746a265c04d7b72fff2ade6fd50d5ca8 Mon Sep 17 00:00:00 2001 From: cmurialdo Date: Thu, 8 Dec 2022 10:26:34 -0300 Subject: [PATCH 1/2] Fix cases of Streams and resources that were not released properly. --- .../GxClasses/Core/GXUtilsCommon.cs | 40 ++++++++-------- .../GxClasses/Domain/GXLDAP.cs | 16 ++++--- .../GxClasses/Printer/GxPrinter.cs | 6 ++- .../GxClasses/Reorg/GXReorg.cs | 48 +++++++++---------- 4 files changed, 56 insertions(+), 54 deletions(-) diff --git a/dotnet/src/dotnetframework/GxClasses/Core/GXUtilsCommon.cs b/dotnet/src/dotnetframework/GxClasses/Core/GXUtilsCommon.cs index 56f32b5fb..9f649f0f6 100644 --- a/dotnet/src/dotnetframework/GxClasses/Core/GXUtilsCommon.cs +++ b/dotnet/src/dotnetframework/GxClasses/Core/GXUtilsCommon.cs @@ -4602,35 +4602,35 @@ public static GxStringCollection DefaultApplicationPoolIdentity() GxStringCollection usernames = new GxStringCollection(); try { - DirectoryEntry Entry = GetAppPoolEntry(); - if (Entry != null) - { - PropertyCollection Properties = Entry.Properties; - string AppPoolIdentityType = Properties["AppPoolIdentityType"][0].ToString().Trim(); - switch (AppPoolIdentityType) + using (DirectoryEntry Entry = GetAppPoolEntry()) { + if (Entry != null) { - case APPPOOL_IDENTITY_TYPE_APPPOOL: + PropertyCollection Properties = Entry.Properties; + string AppPoolIdentityType = Properties["AppPoolIdentityType"][0].ToString().Trim(); + switch (AppPoolIdentityType) + { + case APPPOOL_IDENTITY_TYPE_APPPOOL: #if NETCORE - usernames.Add(IDENTITY_NETCORE_APPPOOL); + usernames.Add(IDENTITY_NETCORE_APPPOOL); #else usernames.Add(IDENTITY_CLASSIC_APPPOOL); usernames.Add(IDENTITY_INTEGRATED_APPPOOL_FW35); usernames.Add(IDENTITY_INTEGRATED_APPPOOL_FW40); #endif - break; - case APPPOOL_IDENTITY_TYPE_NETWORKSERVICE: - case APPPOOL_IDENTITY_TYPE_LOCALSYSTEM: - usernames.Add(IDENTITY_NETWORK_SERVICE); - break; - case APPPOOL_IDENTITY_TYPE_LOCALSERVICE: - usernames.Add(IDENTITY_LOCAL_SERVICE); - break; - case APPPOOL_IDENTITY_TYPE_SPECIFICUSER: - usernames.Add(Properties["WAMUserName"][0].ToString()); - break; + break; + case APPPOOL_IDENTITY_TYPE_NETWORKSERVICE: + case APPPOOL_IDENTITY_TYPE_LOCALSYSTEM: + usernames.Add(IDENTITY_NETWORK_SERVICE); + break; + case APPPOOL_IDENTITY_TYPE_LOCALSERVICE: + usernames.Add(IDENTITY_LOCAL_SERVICE); + break; + case APPPOOL_IDENTITY_TYPE_SPECIFICUSER: + usernames.Add(Properties["WAMUserName"][0].ToString()); + break; + } } } - } catch (Exception ex) { diff --git a/dotnet/src/dotnetframework/GxClasses/Domain/GXLDAP.cs b/dotnet/src/dotnetframework/GxClasses/Domain/GXLDAP.cs index fa3825ca8..da79ac358 100644 --- a/dotnet/src/dotnetframework/GxClasses/Domain/GXLDAP.cs +++ b/dotnet/src/dotnetframework/GxClasses/Domain/GXLDAP.cs @@ -245,14 +245,16 @@ public GxSimpleCollection GetAttribute(string name, string context, GXPr context1 = "/" + context; AuthenticationTypes at = getAuthentication(); _entry = new DirectoryEntry("LDAP://" + getPath() + context1, _user, _password, at); - DirectorySearcher ds = new DirectorySearcher(_entry, filter, new string[] { name }); - foreach (SearchResult result in ds.FindAll()) + using (DirectorySearcher ds = new DirectorySearcher(_entry, filter, new string[] { name })) { - PropertyValueCollection values = (PropertyValueCollection)(result.GetDirectoryEntry().Properties[name]); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < values.Count; i++) - sb.Append(values[i].ToString() + " "); - sc.Add(sb.ToString()); + foreach (SearchResult result in ds.FindAll()) + { + PropertyValueCollection values = (PropertyValueCollection)(result.GetDirectoryEntry().Properties[name]); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < values.Count; i++) + sb.Append(values[i].ToString() + " "); + sc.Add(sb.ToString()); + } } } } diff --git a/dotnet/src/dotnetframework/GxClasses/Printer/GxPrinter.cs b/dotnet/src/dotnetframework/GxClasses/Printer/GxPrinter.cs index f3b8dd6cd..50a70bec5 100644 --- a/dotnet/src/dotnetframework/GxClasses/Printer/GxPrinter.cs +++ b/dotnet/src/dotnetframework/GxClasses/Printer/GxPrinter.cs @@ -1526,8 +1526,10 @@ void DrawBitmap(string bitmap, Point p1, Point p2) "\\pichgoal"+(height * LOGICAL2TWIP).ToString()+ "\n"; streamToWrite.Write( sBuffer); - Bitmap bm = new Bitmap(bitmap); - bm.Save( streamToWrite.BaseStream, ImageFormat.Emf); + using (Bitmap bm = new Bitmap(bitmap)) + { + bm.Save(streamToWrite.BaseStream, ImageFormat.Emf); + } streamToWrite.Write( "}}\n"); } void DrawText(string text, Point p1, Point p2, Font fnt, int align, Color foreColor, Color backColor) diff --git a/dotnet/src/dotnetframework/GxClasses/Reorg/GXReorg.cs b/dotnet/src/dotnetframework/GxClasses/Reorg/GXReorg.cs index 66d76a3ec..cf26810d3 100644 --- a/dotnet/src/dotnetframework/GxClasses/Reorg/GXReorg.cs +++ b/dotnet/src/dotnetframework/GxClasses/Reorg/GXReorg.cs @@ -225,8 +225,6 @@ public ArrayList ParseStmtFile(ReorgScriptType time) public bool BeginResume() { - StreamReader input = null; - try { if (createDataBase || ignoreResume) @@ -235,27 +233,29 @@ public bool BeginResume() } else if (File.Exists(RESUME_REOR_FILE)) { - input = File.OpenText(RESUME_REOR_FILE); - String statement = input.ReadLine(); - if (!string.IsNullOrEmpty(statement)) - { - string timeStamp; - Config.GetValueOf("VER_STAMP", out timeStamp); - if (statement!=timeStamp) - { - AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed1"), null); - AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed2"), null); - AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed3"), null); - GXReorganization.Error = true; - return false; - } - } - while (statement != null) - { - executedStatements[statement] = null; - statement = input.ReadLine(); - } - executingResume = true; + using (StreamReader input = File.OpenText(RESUME_REOR_FILE)) + { + String statement = input.ReadLine(); + if (!string.IsNullOrEmpty(statement)) + { + string timeStamp; + Config.GetValueOf("VER_STAMP", out timeStamp); + if (statement != timeStamp) + { + AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed1"), null); + AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed2"), null); + AddMsg(GXResourceManager.GetMessage("GXM_lastreorg_failed3"), null); + GXReorganization.Error = true; + return false; + } + } + while (statement != null) + { + executedStatements[statement] = null; + statement = input.ReadLine(); + } + executingResume = true; + } } return true; } @@ -268,8 +268,6 @@ public bool BeginResume() finally { #if !NETCORE - if (input != null) - input.Close(); SerializeExecutedStatements(); #endif } From ef0134b7da7eeb722121c6be58eadd3c5bd12246 Mon Sep 17 00:00:00 2001 From: "ARTECH\\sgrampone" Date: Tue, 13 Dec 2022 13:30:44 -0300 Subject: [PATCH 2/2] Closing streams on SecurityAPI's Fortify findings --- .../Keys/CertificateX509.cs | 114 +++++++--------- .../Keys/PrivateKeyManager.cs | 128 ++++++++---------- 2 files changed, 108 insertions(+), 134 deletions(-) diff --git a/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/CertificateX509.cs b/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/CertificateX509.cs index d284efe18..4f649c73a 100644 --- a/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/CertificateX509.cs +++ b/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/CertificateX509.cs @@ -309,51 +309,55 @@ private bool loadPublicKeyFromFile(string path, string alias, string password) private bool loadPublicKeyFromPEMFile(string path) { bool flag = false; - StreamReader streamReader = new StreamReader(path); - PemReader pemReader = new PemReader(streamReader); - Object obj = pemReader.ReadObject(); - if (obj.GetType() == typeof(AsymmetricKeyParameter)) - { - this.error.setError("CE007", "The file contains a private key"); - flag = false; - } - - if (obj.GetType() == typeof(ECPublicKeyParameters)) - { - /*ECPublicKeyParameters ecParms = (ECPublicKeyParameters)obj; - this.subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ecParms); - this.publicKeyAlgorithm = ecParms.AlgorithmName; - this.hasPublicKey = true; - return true;*/ - this.error.setError("CE008", "Invalid X509 Certificate format"); - return false; - } - - if (obj.GetType() == typeof(System.Security.Cryptography.X509Certificates.X509Certificate)) - { - Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; - castCertificate(cert); - closeReaders(streamReader, pemReader); - return true; - - } - if (obj.GetType() == typeof(Org.BouncyCastle.X509.X509Certificate)) - { - Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; - castCertificate(cert); - closeReaders(streamReader, pemReader); - return true; - } - if (obj.GetType() == typeof(X509CertificateStructure)) - { - Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; - castCertificate(cert); - closeReaders(streamReader, pemReader); - return true; - } - - closeReaders(streamReader, pemReader); - return flag; + using (StreamReader streamReader = new StreamReader(path)) + { + PemReader pemReader = new PemReader(streamReader); + Object obj = pemReader.ReadObject(); + try + { + if (obj.GetType() == typeof(AsymmetricKeyParameter)) + { + this.error.setError("CE007", "The file contains a private key"); + flag = false; + } + + if (obj.GetType() == typeof(ECPublicKeyParameters)) + { + /*ECPublicKeyParameters ecParms = (ECPublicKeyParameters)obj; + this.subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ecParms); + this.publicKeyAlgorithm = ecParms.AlgorithmName; + this.hasPublicKey = true; + return true;*/ + this.error.setError("CE008", "Invalid X509 Certificate format"); + return false; + } + + if (obj.GetType() == typeof(System.Security.Cryptography.X509Certificates.X509Certificate)) + { + Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; + castCertificate(cert); + return true; + + } + if (obj.GetType() == typeof(Org.BouncyCastle.X509.X509Certificate)) + { + Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; + castCertificate(cert); + return true; + } + if (obj.GetType() == typeof(X509CertificateStructure)) + { + Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)obj; + castCertificate(cert); + return true; + } + }finally + { + pemReader.Reader.Close(); + } + } + return flag; + } @@ -509,26 +513,6 @@ private bool loadPublicKeyFromPKCS12File(string path, string password) return flag; } - /// - /// Excecute close methods of PemReader and StreamReader data types - /// - /// StreamReader type - /// PemReader type - private void closeReaders(StreamReader streamReader, PemReader pemReader) - { - try - { - streamReader.Close(); - pemReader.Reader.Close(); - } -#pragma warning disable CA1031 // Do not catch general exception types - catch -#pragma warning restore CA1031 // Do not catch general exception types - { - this.error.setError("CE015", "Error closing StreamReader/ PemReader for certificates"); - } - } - private void castCertificate(Org.BouncyCastle.X509.X509Certificate cert) { this.subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cert.GetPublicKey()); diff --git a/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/PrivateKeyManager.cs b/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/PrivateKeyManager.cs index cefa74608..c990038d6 100644 --- a/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/PrivateKeyManager.cs +++ b/dotnet/src/extensions/SecurityAPI/dotnet/dotnetframework/SecurityAPICommons/Keys/PrivateKeyManager.cs @@ -387,84 +387,74 @@ private bool loadPrivateKeyFromPKCS12File(string path, string password) private bool loadPrivateKeyFromPEMFile(string path) { bool flag = false; - StreamReader streamReader = new StreamReader(path); - PemReader pemReader = new PemReader(streamReader); - Object obj = null; - try - { - obj = pemReader.ReadObject(); - }catch(Exception) + using (StreamReader streamReader = new StreamReader(path)) { - if(this.encryptionPassword == null) + PemReader pemReader = new PemReader(streamReader); + Object obj = null; + try { - this.error.setError("PK024", "Password for key decryption is empty"); - return false; - } - try - { - StreamReader sReader = new StreamReader(path); - PemReader pReader = new PemReader(sReader, new PasswordFinder(this.encryptionPassword)); - obj = pReader.ReadObject(); - closeReaders(sReader, pReader); - }catch(Exception ex) + try + { + obj = pemReader.ReadObject(); + } + catch (Exception) + { + if (this.encryptionPassword == null) + { + this.error.setError("PK024", "Password for key decryption is empty"); + return false; + } + try + { + using (StreamReader sReader = new StreamReader(path)) + { + PemReader pReader = new PemReader(sReader, new PasswordFinder(this.encryptionPassword)); + obj = pReader.ReadObject(); + pReader.Reader.Close(); + } + } + catch (Exception ex) + { + this.error.setError("PK023", ex.Message); + return false; + } + } + if (obj.GetType() == typeof(RsaPrivateCrtKeyParameters)) + { + AsymmetricKeyParameter asymKeyParm = (AsymmetricKeyParameter)obj; + this.privateKeyInfo = createPrivateKeyInfo(asymKeyParm); + this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id; + this.hasPrivateKey = true; + return true; + } + if (obj.GetType() == typeof(Pkcs8EncryptedPrivateKeyInfo)) + { + this.error.setError("PK007", "Encrypted key, remove the key password"); + flag = false; + } + if (obj.GetType() == typeof(AsymmetricCipherKeyPair)) + { + AsymmetricCipherKeyPair asymKeyPair = (AsymmetricCipherKeyPair)obj; + this.privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymKeyPair.Private); + this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id; + this.hasPrivateKey = true; + return true; + } + if (obj.GetType() == typeof(X509Certificate)) + { + this.error.setError("PK008", "The file contains a public key"); + flag = false; + + } + }finally { - this.error.setError("PK023", ex.Message); - return false; + pemReader.Reader.Close(); } } - if (obj.GetType() == typeof(RsaPrivateCrtKeyParameters)) - { - AsymmetricKeyParameter asymKeyParm = (AsymmetricKeyParameter)obj; - this.privateKeyInfo = createPrivateKeyInfo(asymKeyParm); - this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id; - this.hasPrivateKey = true; - closeReaders(streamReader, pemReader); - return true; - } - if (obj.GetType() == typeof(Pkcs8EncryptedPrivateKeyInfo)) - { - this.error.setError("PK007", "Encrypted key, remove the key password"); - flag = false; - } - if (obj.GetType() == typeof(AsymmetricCipherKeyPair)) - { - AsymmetricCipherKeyPair asymKeyPair = (AsymmetricCipherKeyPair)obj; - this.privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymKeyPair.Private); - this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id; - this.hasPrivateKey = true; - return true; - } - if (obj.GetType() == typeof(X509Certificate)) - { - this.error.setError("PK008", "The file contains a public key"); - flag = false; - - } - closeReaders(streamReader, pemReader); return flag; } - /// - /// Excecute close methods of PemReader and StreamReader data types - /// - /// StreamReader type - /// PemReader type - private void closeReaders(StreamReader streamReader, PemReader pemReader) - { - try - { - streamReader.Close(); - pemReader.Reader.Close(); - } -#pragma warning disable CA1031 // Do not catch general exception types - catch -#pragma warning restore CA1031 // Do not catch general exception types - { - this.error.setError("PK012", "Error closing StreamReader/ PemReader for certificates"); - } - } - /// /// Build private PrivateKeyInfo /// https://csharp.hotexamples.com/examples/Org.BouncyCastle.Asn1.Pkcs/RsaPrivateKeyStructure/-/php-rsaprivatekeystructure-class-examples.html