2

First of all, my native language is spanish so I'd want to apologize if I write bad some (or all) sentences.

I'm developing an App in Xamarin.android that uses Digital Signature on a PDF document and lately the class I use to stamp the signature had a lot of problems. This is the issue I'm facing now:

Fatal signal 6 (SIGABRT), code -6 in tid 30481 (al.FirmaDigital)

I'm pretty new in Xamarin and I don't have idea why is this going on. I've been investigating and I found that this error occurs when a program sends a signal to abort the process. But I don't know what is causing this error.

I only know this error appears when it run the line 175 of the code: objSignedCms.ComputeSignature(objCmsSigner, false); (I used a try/catch but it doesn't throw any exception. The app just close itself and the logcat sends that error).

I let you here the class I'm using to sign the document so you can see if you can help me.

Thanks in advance!

using System;
using System.Collections.Generic;
using System.Linq;


using System.Collections;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Org.BouncyCastle.X509;
using SysX509 = System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;

namespace FirmaDigital.FirmaDigital
{
    public static class PDF
    {
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        /// FormatPlace. Posibles valores para Lugar de la firma:
        /// A4TL: A4 normal, arriba a la izquierda
        /// A4TR: A4 normal, arriba a la derecha
        /// A4BL: A4 normal, abajo a la izquierda
        /// A4BR: A4 normal, abajo a la derecha
        /// A4aTL: A4 apaisado, arriba a la izquierda
        /// A4aTR: A4 apaisado, arriba a la derecha
        /// A4aBL: A4 apaisado, abajo a la izquierda
        /// A4aBR: A4 apaisado, abajo a la derecha

        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, string FormatPlace, string TSA)
        {
            X509CertificateParser objCP = new X509CertificateParser();
            X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            PdfReader objReader = new PdfReader(Source);
            PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0');
            PdfSignatureAppearance objSA = objStamper.SignatureAppearance;

            int LastPage = objReader.NumberOfPages;

            if (AddVisibleSign)
            {
                switch (FormatPlace)
                {
                    case "A4TL":
                        objSA.SetVisibleSignature(new Rectangle(50, 750, 300, 780), LastPage, null);
                        break;
                    case "A4TR":
                        objSA.SetVisibleSignature(new Rectangle(350, 750, 600, 780), LastPage, null);
                        break;
                    case "A4BL":
                        objSA.SetVisibleSignature(new Rectangle(50, 50, 300, 80), LastPage, null);
                        break;
                    case "A4BR":
                        objSA.SetVisibleSignature(new Rectangle(350, 50, 600, 80), LastPage, null);
                        break;
                    case "A4aTL":
                        objSA.SetVisibleSignature(new Rectangle(50, 570, 300, 600), LastPage, null);
                        break;
                    case "A4aTR":
                        objSA.SetVisibleSignature(new Rectangle(530, 570, 780, 600), LastPage, null);
                        break;
                    case "A4aBL":
                        objSA.SetVisibleSignature(new Rectangle(50, 20, 300, 50), LastPage, null);
                        break;
                    case "A4aBR":
                        objSA.SetVisibleSignature(new Rectangle(530, 20, 780, 50), LastPage, null);
                        break;
                }
            }

            objSA.SignDate = DateTime.Now;
            objSA.Certificate = objChain[0];
            objSA.Reason = Reason;
            objSA.Location = Location;
            objSA.Acro6Layers = true;
            objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = "Nombre de Prueba";
            if (objSA.Reason != null)
                objSignature.Reason = objSA.Reason;
            if (objSA.Location != null)
                objSignature.Location = objSA.Location;
            objSA.CryptoDictionary = objSignature;
            int intCSize = 4000;
            Hashtable objTable = new Hashtable();
            objTable[PdfName.CONTENTS] = intCSize * 2 + 2;

            var dict = HashtableToDictionary<PdfName, int>(objTable);

            objSA.PreClose(dict);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.GetRangeStream();
            int intRead = 0;
            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK = SignMsg(objSHA1.Hash, Certificate, false, Source, TSA);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
            objSA.Close(objDict);
        }

        public static Dictionary<K, V> HashtableToDictionary<K, V>(Hashtable table)
        {
            return table
              .Cast<DictionaryEntry>()
              .ToDictionary(kvp => (K)kvp.Key, kvp => (V)kvp.Value);
        }

        /// <summary>
        /// Crea la firma CMS/PKCS #7
        /// </summary>
        private static byte[] SignMsg(byte[] Message, SysX509.X509Certificate2 SignerCertificate, bool Detached, string Source, string TSA)
        {
            try
            {
                //Creamos el contenedor
                ContentInfo contentInfo = new ContentInfo(Message);

                //Instanciamos el objeto SignedCms con el contenedor
                SignedCms objSignedCms = new SignedCms(contentInfo, Detached);

                //Creamos el "firmante"
                CmsSigner objCmsSigner = new CmsSigner(SignerCertificate);

                // Include the following line if the top certificate in the
                // smartcard is not in the trusted list.
                objCmsSigner.IncludeOption = SysX509.X509IncludeOption.EndCertOnly;
                if (TSA != "S/TSA"){
                    objCmsSigner.UnsignedAttributes.Add(timeData);
                }

                //  Sign the CMS/PKCS #7 message. The second argument is needed to ask for the pin.
                objSignedCms.ComputeSignature(objCmsSigner, false);

                //Encodeamos el mensaje CMS/PKCS #7
                return objSignedCms.Encode();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

[Edit]

I'll let you here the last 10 lines of the logcat:

09-13 13:54:55.788 D/Mono    (18211): Assembly Ref addref System.Security.Cryptography.Algorithms[0x9c119fa0] -> mscorlib[0xb46d4580]: 18
Loaded assembly: System.Security.Cryptography.Algorithms.dll [External]
09-13 13:54:55.864 D/Mono    (18211): Assembly Ref addref 
System.Security.Cryptography.Algorithms[0x9c119fa0] -> System.Core[0xb477c4c0]: 5
09-13 13:54:55.881 D/Mono    (18211): Assembly Ref addref System.Memory[0xb46d4b20] -> System.Runtime.CompilerServices.Unsafe[0xb46d4be0]: 2
09-13 13:54:55.882 D/Mono    (18211): Unloading image System.Runtime.dll [0x9e0e8300].
09-13 13:54:55.883 D/Mono    (18211): Image addref System.Runtime[0x9c119e80] -> System.Runtime.dll[0xb4447000]: 5
09-13 13:54:55.883 D/Mono    (18211): Config attempting to parse: 'System.Runtime.dll.config'.
09-13 13:54:55.883 D/Mono    (18211): Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Runtime/System.Runtime.config'.
09-13 13:54:55.883 D/Mono    (18211): Assembly Ref addref System.Runtime.CompilerServices.Unsafe[0xb46d4be0] -> System.Runtime[0xb46d4dc0]: 3
09-13 13:54:55.887 F/        (18211): * Assertion at /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mono/mini/method-to-ir.c:13643, condition `ins->opcode >= MONO_CEE_LAST' not met
09-13 13:54:55.887 F/libc    (18211): Fatal signal 6 (SIGABRT), code -6 in tid 18211 (al.FirmaDigital)

[Edit 2]

This is the logcat after doing what @SushiHangover told me to do:

09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE not know revents:0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 0 poll events 1 revents 0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 1 poll events 1 revents 0
09-14 11:33:04.450  Hipstreet 7DTB40    Error   23079   libc    Fatal signal 6 (SIGABRT), code -6 in tid 23079 (al.FirmaDigital)
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE aed_main_fork_worker: generator 0xb6437148, worker 0xbec4c928, recv_fd 0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE not know revents:0
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE $===AEE===AEE===AEE===$
09-14 11:33:04.450  Hipstreet 7DTB40    Debug   230 AEE p 2 poll events 1 revents 1
09-14 11:33:04.449  Hipstreet 7DTB40    Error   23079       * Assertion at /Users/builder/jenkins/workspace/xamarin-android/xamarin-android/external/mono/mono/mini/method-to-ir.c:13643, condition `ins->opcode >= MONO_CEE_LAST' not met
09-14 11:33:04.443  Hipstreet 7DTB40    Debug   23079   Mono    Assembly Ref addref System.Runtime.CompilerServices.Unsafe[0xb46d4be0] -> System.Runtime[0xb46d4dc0]: 3
09-14 11:33:04.443  Hipstreet 7DTB40    Debug   23079   Mono    Config attempting to parse: '/usr/local/etc/mono/assemblies/System.Runtime/System.Runtime.config'.
09-14 11:33:04.442  Hipstreet 7DTB40    Debug   23079   Mono    Config attempting to parse: 'System.Runtime.dll.config'.
Matias
  • 123
  • 6
  • Add the full `logcat` crash to your question (https://stackoverflow.com/questions/36693887/what-is-fatal-signal-6-in-android-logcat) – SushiHangover Sep 13 '18 at 15:47
  • Whenever a problem mysteriously enters my Xamarin apps I update all Nuget packages, visual studio, xamarin, anrdoid libraries and nearly always that fixes it. It's like a time-bomb. – noelicus Sep 13 '18 at 15:52
  • @SushiHangover I edited the question so you can see the logcat. Also already saw the link you added a few days ago, and it didn't work for me. – Matias Sep 13 '18 at 19:10
  • What is the output when setting `mono` to display a higher level of logging (`adb shell setprop debug.mono.env "'MONO_LOG_LEVEL=info'"` do this *before* running the app) as there might be related msgs to the problem (i.e. a tailcall issue), review the source code for the assertion details: https://github.com/mono/mono/blob/master/mono/mini/method-to-ir.c#L12430 – SushiHangover Sep 13 '18 at 19:29
  • @SushiHangover I edited the question once again, the error persists – Matias Sep 14 '18 at 14:41

0 Answers0