Esempio n. 1
0
        private void TreeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if ((string)e.Node.Tag != "CMD")
            {
                return;
            }
            String       cmd   = e.Node.Text;
            String       descr = e.Node.Parent.Text;
            QueueMessage msg   = new QueueMessage();

            String Reply = get_value(cmd, descr, false, ref msg);

            if (Reply != "")
            {
                MessageBox.Show(String.Format("Received [ {0} ]", Globs.Super_Clean(Reply)));
            }
        }
Esempio n. 2
0
        public PcrSelection PcrBank(PcrSelection[] pcrBanks, TpmAlgId hashAlg)
        {
            // The hash algorithm is not supported by Tpm2Tester
            if (!CryptoLib.IsSupported(hashAlg))
            {
                return(null);
            }

            foreach (var pb in pcrBanks)
            {
                if (pb.hash == hashAlg)
                {
                    return(pb);
                }
            }
            Globs.Throw("No PCR bank for hash algorithm " + hashAlg);
            return(null);
        }
Esempio n. 3
0
        // Heuristics to return a suitable frame to report as part of an error report.
        // Returns the first entity in the stack with a tester-attribute.
        public static StackFrame[] GetFramesToReport(StackTrace s)
        {
            if (s == null)
            {
                return(new StackFrame[0]);
            }

            StackFrame[] stackFrames = s.GetFrames();
            if (stackFrames == null)
            {
                return(new StackFrame[0]);
            }
            var  framesToReport  = new List <StackFrame>();
            bool reportThisFrame = false;

            for (int j = 0; j < stackFrames.Length; j++)
            {
                StackFrame f = stackFrames[j];
                MethodBase b = f.GetMethod();
                MethodInfo m = b is MethodInfo ? (MethodInfo)b : null;
                if (m == null)
                {
                    Debug.Assert(!reportThisFrame);
                    continue;
                }
                if (reportThisFrame)
                {
                    framesToReport.Add(f);
                }
                if (Globs.GetAttr <TestAttribute>(f.GetMethod()) != null)
                {
                    if (!reportThisFrame)
                    {
                        framesToReport.Add(f);
                    }
                    break;
                }
                reportThisFrame = Globs.GetAttr <TpmCommandAttribute>(f.GetMethod()) != null ||
                                  f.GetMethod().ToString().Contains("Void Test(");
            }
            return(framesToReport.ToArray());
        }
Esempio n. 4
0
        public static Tpm2bDigest[] SafePcrRead(Tpm2 tpm, PcrSelection sel)
        {
            PcrSelection[] selOut;
            var            selIn     = new PcrSelection[] { sel.Copy() };
            var            pcrValues = new Tpm2bDigest[0];

            do
            {
                Tpm2bDigest[] vals;
                tpm.PcrRead(selIn, out selOut, out vals);
                pcrValues = pcrValues.Concat(vals).ToArray();
                Debug.Assert(selOut.Length == 1);
                // The first part of the while condition is used to by pass not
                // implemented PCRs
            } while (!Globs.IsZeroBuffer(selOut[0].pcrSelect) &&
                     selIn[0].Clear(selOut[0]));
            Debug.Assert(selIn[0].GetSelectedPcrs().Length == 0);
            Debug.Assert(sel.GetSelectedPcrs().Length == pcrValues.Length);
            return(pcrValues);
        }
Esempio n. 5
0
        public static _AcDb.ResultBuffer GetNonPlottableLayers(_AcDb.ResultBuffer rb)
        {
            List <string> layerNames = new List <string>();

            Globs.GetNonPlottableLayers(layerNames);

            if (layerNames.Count > 0)
            {
                _AcDb.ResultBuffer rbRet = new _AcDb.ResultBuffer();
                foreach (var name in layerNames)
                {
                    rbRet.Add(new _AcDb.TypedValue((int)_AcBrx.LispDataType.Text, name));
                }
                return(rbRet);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 6
0
 public bool IsResettablePcr(Tpm2 tpm, int pcr, int locality = 0)
 {
     byte[] resettablePcrs = ResettablePcrs;
     if (locality == 4)
     {
         // In accordance with PTP 3.7.1:
         // "Note that since the hardware that performs the DRTM sequence at
         // Locality 4 is not capable of doing TPM2_PCR_Reset(), the TPM_PT_PCR_RESET_L4
         // attribute is repurposed to indicate the initial state of the PCR(0 or - 1)
         // and to indicate which PCR are set to 0 by a successful DRTM Sequence.
         return(false);
     }
     if (locality != 0)
     {
         var props = new PtPcr[] { PtPcr.ResetL1, PtPcr.ResetL2,
                                   PtPcr.ResetL3, PtPcr.ResetL4 };
         resettablePcrs = Tpm2.GetPcrProperty(tpm, props[locality - 1]);
     }
     return(Globs.IsBitSet(resettablePcrs, (int)pcr));
 }
Esempio n. 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Test();
                return;

#if ARX_APP
                ResultBuffer rbInvoke = new ResultBuffer();
                rbInvoke.Add(new TypedValue((int)(_AcBrx.LispDataType.Text), "alx_F:ino_plan2_GetConfiguration"));
                ResultBuffer resInvoke = _AcAp.Application.Invoke(rbInvoke);
                rbInvoke.Dispose();

                object o1 = Globs.GetLispVariable("alx_V:ino_flattrib");
                object o2 = Globs.GetLispVariable("alx_V:ino_flattribdfa");

                object o3 = Globs.LispFindFile("plan2.cfg");
                if (o3 != null)
                {
                    object o4 = Globs.LispTryLoadGlobs(o3.ToString());
                }
#endif

                //rbInvoke = new ResultBuffer();
                //rbInvoke.Add(new TypedValue((int)(Autodesk.AutoCAD.Runtime.LispDataType.Text), "alx_F:ino_EvalLispVariable"));
                //rbInvoke.Add(new TypedValue((int)(Autodesk.AutoCAD.Runtime.LispDataType.Text), "alx_V:ino_flattrib"));
                //resInvoke = _AcAp.Application.Invoke(rbInvoke);
                //rbInvoke.Dispose();

                //rbInvoke = new ResultBuffer();
                //rbInvoke.Add(new TypedValue((int)(Autodesk.AutoCAD.Runtime.LispDataType.Text), "alx_F:ino_EvalLispVariable"));
                //rbInvoke.Add(new TypedValue((int)(Autodesk.AutoCAD.Runtime.LispDataType.Text), "alx_V:ino_flattribxdf"));
                //resInvoke = _AcAp.Application.Invoke(rbInvoke);
                //rbInvoke.Dispose();
            }
            catch (Exception ex)
            {
                string x = ex.Message;
                ;
            }
        }
Esempio n. 8
0
        public static void Plan2InsertFehlerLines(_AcDb.ResultBuffer rb)
        {
            var arr = rb.AsArray();

            if (arr.Length < 6)
            {
                return;
            }
            string layer = arr[0].Value.ToString();
            // length 1
            // angle 2
            // colorindex 3
            // LB 4

            List <_AcGe.Point3d> pts = new List <_AcGe.Point3d>();

            for (int i = 5; i < arr.Length - 1; i++)
            {
                pts.Add((_AcGe.Point3d)arr[i].Value);
            }
            Globs.InsertFehlerLines(pts, layer);
        }
Esempio n. 9
0
        private static bool GetMansfen(string msg, ref _AcDb.ObjectId mf)
        {
            _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcEd.Editor   ed  = doc.Editor;

            while (true)
            {
                var res = ed.GetEntity(msg);
                if (res.Status == _AcEd.PromptStatus.Cancel)
                {
                    return(false);
                }
                if (res.Status == _AcEd.PromptStatus.OK)
                {
                    if (IsMansfen(res.ObjectId))
                    {
                        mf = res.ObjectId;
                        Globs.HightLight(mf, onOff: true);
                        return(true);
                    }
                }
            }
        }
Esempio n. 10
0
        private void btnFlaBereinig_Click(object sender, EventArgs e)
        {
            if (_FlaBereinigShield)
            {
                return;
            }
            try
            {
                _FlaBereinigShield = true;

                Globs.CancelCommand();

                _AcAp.Application.DocumentManager.MdiActiveDocument.SendStringToExecute("Plan2FlaBereinig ", true, false, false);
            }
            catch (Exception ex)
            {
                _AcAp.Application.ShowAlertDialog(ex.Message);
            }
            finally
            {
                _FlaBereinigShield = false;
            }
        }
Esempio n. 11
0
        public TpmHandle GenerateRsaEncryptionKeyPair(AuthValue ownerAuth, out TpmPublic keyPublic, byte[] keyAuth, TpmHandle persistantHandle)
        {
            var sensCreate = new SensitiveCreate(keyAuth, new byte[0]);

            TpmPublic keyTemplate = new TpmPublic(
                TpmAlgId.Sha1,
                ObjectAttr.UserWithAuth | ObjectAttr.Decrypt |
                ObjectAttr.FixedParent | ObjectAttr.FixedTPM |
                ObjectAttr.SensitiveDataOrigin,
                new byte[0],
                new RsaParms(
                    new SymDefObject(),                                 //a unrestricted decryption key
                    new NullAsymScheme(),                               //not a signing key
                    2048,
                    0),
                new Tpm2bPublicKeyRsa());

            byte[] outsideInfo      = Globs.GetRandomBytes(8);
            var    creationPcrArray = new PcrSelection[0];


            TpmHandle h = tpm[ownerAuth].CreatePrimary(
                TpmRh.Owner,
                sensCreate,
                keyTemplate,
                outsideInfo,
                creationPcrArray,
                out keyPublic,
                out CreationData creationData,
                out byte[] creationHash,
                out TkCreation creationTicket);

            tpm.EvictControl(TpmHandle.RhOwner, h, persistantHandle);

            return(h);
        }
Esempio n. 12
0
        // Returns reference to the byte buffer containing unique value of inPub.
        // Note that in case of ECC keys, the returned buffer references only the
        // first half of the unique value (i.e. x-coordinate of the ECC point).
        public static FieldInfo GetUniqueBuffer(TpmPublic pub, out byte[] buf)
        {
            var keyType = pub.parameters.GetUnionSelector();

            buf = null;
            switch (keyType)
            {
            case TpmAlgId.Rsa:
                buf = (pub.unique as Tpm2bPublicKeyRsa).buffer;
                return(pub.unique.GetType().GetField("buffer"));

            case TpmAlgId.Ecc:
                buf = (pub.unique as EccPoint).x;
                return(pub.unique.GetType().GetField("x"));

            case TpmAlgId.Symcipher:
            case TpmAlgId.Keyedhash:
                buf = (pub.unique as Tpm2bDigest).buffer;
                return(pub.unique.GetType().GetField("buffer"));
            }
            Globs.Throw <NotImplementedException>(
                "GetUniqueBuffer: Unknown TpmPublic type " + keyType);
            return(null);
        }
Esempio n. 13
0
        /// <summary>
        /// Illustrates various cases of automatic authorization handling.
        /// </summary>
        static void AutomaticAuth(Tpm2 tpm)
        {
            TpmHandle primHandle = CreateRsaPrimaryKey(tpm);

            TpmPublic keyPublic;
            TpmHandle keyHandle = CreateSigningDecryptionKey(tpm, primHandle, out keyPublic);

            byte[] message = Globs.GetRandomBytes(32);

            IAsymSchemeUnion decScheme = new SchemeOaep(TpmAlgId.Sha1);
            ISigSchemeUnion  sigScheme = new SchemeRsassa(TpmAlgId.Sha1);

            //
            // TSS.Net implicitly creates an auth session to authorize keyHandle.
            // It uses the auth value cached in the TpmHandle object.
            //
            byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, null);

            Console.WriteLine("Automatic authorization of a decryption key.");

            //
            // An auth session is added automatically when TPM object is not in strict mode.
            //
            byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, null);

            byte[] nonceTpm;

            Console.WriteLine("Session object construction.");

            //
            // If a session with specific properties is required, an AuthSession object
            // can be built from the session handle returned by the TPM2_StartAuthSession
            // command concatenated, if necessary, with session flags and unencrypted salt
            // value (not used in this example).
            //
            AuthSession auditSess = tpm.StartAuthSession(
                TpmRh.Null,                             // no salt
                TpmRh.Null,                             // no bind object
                Globs.GetRandomBytes(16),               // nonceCaller
                null,                                   // no salt
                TpmSe.Hmac,                             // session type
                new SymDef(),                           // no encryption/decryption
                TpmAlgId.Sha256,                        // authHash
                out nonceTpm)
                                    + (SessionAttr.ContinueSession | SessionAttr.Audit);

            /*
             * Alternatively one of the StartAuthSessionEx helpers can be used). E.g.
             *
             * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256,
             *                                  SessionAttr.ContinueSession | SessionAttr.Audit);
             */

            //
            // TSS.Net specific call to verify TPM auditing correctness.
            //
            tpm._SetCommandAuditAlgorithm(TpmAlgId.Sha256);

            Console.WriteLine("Automatic authorization using explicitly created session object.");

            //
            // Appropriate auth value is added automatically into the provided session.
            //
            // Note that the call to _Audit() is optional and is only used when one
            // needs the TSS.Net framework to compute the audit digest on its own (e.g.
            // when simulating the TPM functionality without access to an actual TPM).
            //
            byte[] decrypted2 = tpm[auditSess]._Audit()
                                .RsaDecrypt(keyHandle, encrypted, decScheme, null);

            ISignatureUnion signature;
            Attest          attest;

            //
            // A session is added automatically to authorize usage of the permanent
            // handle TpmRh.Endorsement.
            //
            // Note that if auth value of TpmRh.Endorsement is not empty, you need to
            // explicitly assign it to the tpm.EndorsementAuth property of the given
            // Tpm2 object.
            //
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess,
                                               null, new NullSigScheme(), out signature);

            //
            // But if the corresponding auth value stored in the Tpm2 object is invalid, ...
            //
            AuthValue endorsementAuth = tpm.EndorsementAuth;

            tpm.EndorsementAuth = Globs.ByteArray(16, 0xde);

            //
            // ... the command will fail.
            //
            tpm._ExpectError(TpmRc.BadAuth)
            .GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess,
                                   null, new NullSigScheme(), out signature);
            //
            // Restore correct auth value.
            //
            tpm.EndorsementAuth = endorsementAuth;

            //
            // Verify that decryption worked correctly.
            //
            Debug.Assert(Globs.ArraysAreEqual(decrypted1, decrypted2));

            //
            // Verify that auditing worked correctly.
            //
            SessionAuditInfo info = (SessionAuditInfo)attest.attested;

            Debug.Assert(Globs.ArraysAreEqual(info.sessionDigest, tpm._GetAuditHash().HashData));

            Console.WriteLine("Auth value tracking by TSS.Net.");

            //
            // Change auth value of the decryption key.
            //
            TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, primHandle, AuthValue.FromRandom(16));
            TpmHandle  newKeyHandle  = tpm.Load(primHandle, newKeyPrivate, keyPublic);

            //
            // Allow non-exclusive usage of the audit session.
            //
            auditSess.Attrs &= ~SessionAttr.AuditExclusive;

            //
            // Correct auth value (corresponding to newKeyHandle, and different from
            // the one used for keyHandle) will be added to auditSess.
            //
            decrypted1 = tpm[auditSess]._Audit()
                         .RsaDecrypt(newKeyHandle, encrypted, decScheme, null);

            Console.WriteLine("Automatic authorization with multiple sessions.");

            //
            // Now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle).
            //
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess,
                                               null, sigScheme, out signature);

            //
            // Verify that the previous command worked correctly.
            //
            bool sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest),
                                                           signature);

            Debug.Assert(sigOk);

            //
            // In the following example the first session is generated based on session
            // type indicator (Auth.Pw), and the second one is added automatically.
            //
            attest = tpm[Auth.Pw].GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess,
                                                        null, sigScheme, out signature);

            //
            // Verify that the previous command worked correctly.
            //
            sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest),
                                                      signature);
            Debug.Assert(sigOk);

            //
            // Release TPM resources that we do not need anymore.
            //
            tpm.FlushContext(newKeyHandle);
            tpm.FlushContext(auditSess);

            //
            // The following example works correctly only when TPM resource management
            // is not enabled (e.g. with TPM simulator, or when actual TPM is in raw mode).
            //
            if (!tpm._GetUnderlyingDevice().HasRM())
            {
                Console.WriteLine("Using session type indicators.");

                //
                // Deplete TPM's active session storage
                //
                List <AuthSession> landfill = new List <AuthSession>();

                for (;;)
                {
                    tpm._AllowErrors();
                    AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256,
                                                           SessionAttr.ContinueSession);
                    if (!tpm._LastCommandSucceeded())
                    {
                        break;
                    }
                    landfill.Add(s);
                }

                //
                // Check if session type indicators are processed correctly
                //
                tpm[Auth.Hmac]._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);
                //
                // Password authorization protocol session uses a predefined handle value,
                // so it must work even when there are no free session slots in the TPM.
                //
                tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);

                //
                // Check if default session type defined by the TPM device is processed correctly.
                //
                bool needHmac = tpm._GetUnderlyingDevice().NeedsHMAC;

                tpm._GetUnderlyingDevice().NeedsHMAC = true;

                tpm._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);

                tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);

                tpm._GetUnderlyingDevice().NeedsHMAC = false;

                tpm.RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);
                tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null);

                tpm._GetUnderlyingDevice().NeedsHMAC = needHmac;

                landfill.ForEach(s => tpm.FlushContext(s));
            }

            //
            // Release TPM resources.
            //
            tpm.FlushContext(keyHandle);
            tpm.FlushContext(primHandle);

            Console.WriteLine("Done.");
        }
Esempio n. 14
0
        public static void Plan2AufteilungNet()
        {
            var acadApp = (Autodesk.AutoCAD.Interop.AcadApplication)_AcAp.Application.AcadApplication;

            _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcDb.Database db  = doc.Database;
            _AcEd.Editor   ed  = doc.Editor;
            try
            {
                ed.Command("_.LAYER", "_TH", "*", "_ON", "*", "_UN", "*", "");
                var selOp = new _AcEd.PromptSelectionOptions();
                selOp.MessageForAdding = "Zu verschiebende Elemente wählen: ";
                _AcEd.SelectionFilter filter = new _AcEd.SelectionFilter(new _AcDb.TypedValue[] {
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.Operator, "<NOT"),
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.Operator, "<AND"),
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.Start, "*POLYLINE"),
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.LayerName, "A_AL_MANSFEN"),
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.Operator, "AND>"),
                    new _AcDb.TypedValue((int)_AcDb.DxfCode.Operator, "NOT>")
                });
                while (true)
                {
                    var res = ed.GetSelection(selOp, filter);
                    if (res.Status != _AcEd.PromptStatus.OK)
                    {
                        break;
                    }
                    else
                    {
                        var            ss     = res.Value;
                        var            selOpE = new _AcEd.PromptSelectionOptions();
                        _AcDb.ObjectId mf1    = default(_AcDb.ObjectId);
                        if (!GetMansfen("Quell-Mansfen wählen: ", ref mf1))
                        {
                            break;
                        }
                        _AcDb.ObjectId mf2 = default(_AcDb.ObjectId);
                        if (!GetMansfen("Ziel-Mansfen wählen: ", ref mf2))
                        {
                            break;
                        }

                        if (!SameMansfens(mf1, mf2))
                        {
                            ed.WriteMessage("\nDie gewählten Mansfens sind nicht identisch!");
                            System.Windows.Forms.MessageBox.Show("\nDie gewählten Mansfens sind nicht identisch!", "Plan2AufteilungNet");
                        }
                        else
                        {
                            _AcGe.Point3d fromPoint = GetLuPoint(mf1);
                            _AcGe.Point3d toPoint   = GetLuPoint(mf2);

                            string dwgName     = doc.Name;
                            var    dwgProposal = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dwgName), System.IO.Path.GetFileNameWithoutExtension(dwgName) + "_X.dwg");
                            _AcWnd.SaveFileDialog             sfd = new _AcWnd.SaveFileDialog("Ziel-Zeichnung", dwgProposal, "dwg", "TargetDrawing", _AcWnd.SaveFileDialog.SaveFileDialogFlags.NoFtpSites);
                            System.Windows.Forms.DialogResult dr  = sfd.ShowDialog();
                            if (dr == System.Windows.Forms.DialogResult.OK)
                            {
                                var ucs        = ed.CurrentUserCoordinateSystem;
                                var fromPointU = Globs.TransWcsUcs(fromPoint); // fromPoint.TransformBy(ucs);
                                var toPointU   = Globs.TransWcsUcs(toPoint);   // toPoint.TransformBy(ucs);


                                // only acad2015 -
                                ed.Command("_.UNDO", "_M");

                                ed.Command("_.DIMDISASSOCIATE", ss, "");

                                ed.Command("_.MOVE", ss, "", fromPointU, toPointU);
                                //ed.Command("_.MOVE", ss, "", "0,0", "100,100");
                                ed.Command("_.ERASE", "_ALL", "_R", ss, mf2, "");

                                doc.Database.SaveAs(sfd.Filename, false, _AcDb.DwgVersion.Current, doc.Database.SecurityParameters);

                                ed.Command("_.UNDO", "_B");
                                //doc.SendStringToExecute("._UNDO B", true, false, true);
                                // also supports acad2013
                                doc.SendStringToExecute(".'_UNDO M ", true, false, true);
                                //acadApp.ActiveDocument.SendCommand("_.UNDO _M\n");
                                //acadApp.ActiveDocument.SendCommand("_.DIMDISASSOCIATE _P \n");
                            }
                        }

                        Globs.HightLight(mf1, onOff: false);
                        Globs.HightLight(mf2, onOff: false);
                    }
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, "Fehler in (Plan2AufteilungNet): {0}", ex.Message);
                ed.WriteMessage("\n" + msg);
                System.Windows.Forms.MessageBox.Show(ex.Message, "Plan2AufteilungNet");
            }
        }
Esempio n. 15
0
 string GetDefinedProfileNamesList()
 {
     return(ListToString(Globs.ConvertAll(DefinedProfiles, item => item.ProfileName))
            + ", " +
            ListToString(Enum.GetNames(typeof(Category))));
 }
Esempio n. 16
0
        // This is installed as the raw command callback handler on the underlying TPM.
        // It is used to generate low-level test statistics (number of commands executed,
        // etc.), dumps of the conversation with the TPM and to keep a record of all
        // command sequences seen that contain types that we haven't seen before.
        // In the case of a multi-context TPM this will be called on different threads,
        // but locking should be handled safely by MainTestLogger.
        void ICommandCallbacks.PostCallback(byte[] inBuf, byte[] outBuf)
        {
            TimeSpan cmdExecutionTime = DateTime.Now - CurCmdStartTime;

            if (inBuf.Length < 10)
            {
                return;
            }
            Marshaller m           = new Marshaller(inBuf);
            TpmSt      sessionTag  = m.Get <TpmSt>();
            uint       parmSize    = m.Get <UInt32>();
            TpmCc      commandCode = m.Get <TpmCc>();

            if (commandCode == TpmCc.Clear)
            {
                ClearWasExecuted = true;
            }

            Marshaller mOut              = new Marshaller(outBuf);
            TpmSt      responseTag       = mOut.Get <TpmSt>();
            uint       responseParamSize = mOut.Get <uint>();
            TpmRc      responseCode      = mOut.Get <TpmRc>();

            if (ValidateTestAttributes)
            {
                // ValidateTestAttributes should not be set for a stress run
                LogTestAttributes(sessionTag, commandCode);
                try
                {
                    if (responseCode == TpmRc.Success)
                    {
                        ValidateHandleUsage(commandCode, inBuf);
                    }
                }
                catch (Exception)
                {
                    // Invalid command buffer can mess this up
                }
            }

            if (sessionTag.Equals(TpmSt.Null))
            {
                return;
            }

            // There are two encoding for errors - formats 0 and 1. Decode the error type
            uint resultCodeValue    = (uint)responseCode;
            bool formatOneErrorType = ((resultCodeValue & 0x80) != 0);
            uint resultCodeMask     = formatOneErrorType ? 0xBFU : 0x97FU;

            TpmRc maskedError = (TpmRc)((uint)responseCode & resultCodeMask);

            lock (this)
            {
                // log the command info to the test logger so that it can collect stats
                LogCommandExecution(commandCode, maskedError, cmdExecutionTime);
            }

#if false
            // Keep a copy of successfully executed commands that contain types we have
            // not seen so far. This is for tests that need good-command candidate strings,
            // like TestCommandDispatcherCoverage.
            // Code 0x80280400 is returned by TBS when the command is blocked by Windows.
            if (maskedError == TpmRc.Success && !Tpm2.IsTbsError(resultCodeValue))
            {
                // look at all types in command string.  If we have a new type we keep it
                CrackedCommand cc   = CommandProcessor.CrackCommand(inBuf);
                CommandInfo    info = CommandInformation.Info.First(x =>
                                                                    x.CommandCode == cc.Header.CommandCode);
                byte[] inStructBytes = Globs.Concatenate(
                    Globs.GetZeroBytes((int)info.HandleCountIn * 4),
                    cc.CommandParms);
                Marshaller mx = new Marshaller(inStructBytes);

                TpmStructureBase bb = (TpmStructureBase)mx.Get(info.InStructType, "");

                // If a new type is contained, save this command for testing in
                // TestDispatcherCoverage.
                if (HasNewTypes(bb))
                {
                    ExecutedCommandInfo.Add(inBuf);
                }
            }
            else
#else
            if (maskedError != TpmRc.Success)
#endif
            {
                // If a command failed, we can get here only if the corresponding
                // expected error assertion was specified.
                ++NumAsserts;
            }
            ReportProgress();

            // output TPM IO to a text file for later processing
            if (Logger.LogTpmIo)
            {
                while (TpmIoWriter == null)
                {
                    try
                    {
                        string ioLogPath;
                        if (Logger.LogPath != null)
                        {
                            ioLogPath = System.IO.Path.Combine(Logger.LogPath, "tpm_io.txt");
                        }
                        else
                        {
                            string fileName;
                            lock (this)
                            {
                                fileName = "tpm_io-" + DateTime.Now.ToString("yyyy-MMM-dd-HH");
                                if (PrevLogName == fileName)
                                {
                                    fileName += "(" + ++PrevLogInstance + ")";
                                }
                                else
                                {
                                    PrevLogName     = fileName;
                                    PrevLogInstance = 1;
                                }
                            }
                            fileName += ".txt";

#if TSS_MIN_API
                            ioLogPath = fileName;
#else
                            string docsPath = Environment.GetFolderPath(
                                Environment.SpecialFolder.MyDocuments);
                            ioLogPath = System.IO.Path.Combine(docsPath, fileName);
#endif
                        }

                        TpmIoWriter = new StreamWriter(new FileStream(ioLogPath,
                                                                      FileMode.Create));
                        Logger.WriteToLog("Dumping TPM I/O to " + ioLogPath);
                    }
                    catch (Exception e)
                    {
                        string message = "Failed to open the tpm_io.txt file for writing.\n" +
                                         "Error: " + e.Message;
                        Logger.WriteErrorToLog(message);
                    }
                }

                // get the test source code line that initiated the command
                string caller = "unknown";
#if !TSS_NO_STACK
                StackTrace   trace      = new StackTrace(true);
                StackFrame[] frames     = trace.GetFrames();
                int          frameCount = frames.Length;
                StackFrame   f          = null;
                // start at 1 to not count the currently executing function
                for (int j = 1; j < frameCount; j++)
                {
                    f = frames[j];
                    if (f.GetMethod().DeclaringType.Assembly == Logger.TestAssembly)
                    {
                        caller = f.GetFileName() + ":" + f.GetFileLineNumber();
                        break;
                    }
                }
#endif
                string commandCodeString = Enum.GetName(typeof(TpmCc), commandCode);
                string inString          = "{MALFORMED COMMAND BUFFER}";
                string outString         = "{MALFORMED RESPONSE BUFFER}";

                try { inString = CommandProcessor.ParseCommand(inBuf); }
                catch (Exception) { }
                try { outString = CommandProcessor.ParseResponse(commandCodeString, outBuf); }
                catch (Exception) { }

                lock (this)
                {
                    TpmIoWriter.WriteLine(commandCode);
                    TpmIoWriter.WriteLine(caller);

                    TpmIoWriter.WriteLine(">>>> Raw input");
                    TpmIoWriter.WriteLine(Globs.HexFromByteArray(inBuf));
                    TpmIoWriter.WriteLine(">>>> Raw output");
                    TpmIoWriter.WriteLine(Globs.HexFromByteArray(outBuf));

                    TpmIoWriter.WriteLine(">>>> Parsed input");
                    TpmIoWriter.WriteLine(inString);
                    TpmIoWriter.WriteLine(">>>> Parsed output");
                    TpmIoWriter.WriteLine(outString);

                    TpmIoWriter.WriteLine("-----------------------------------------");
                    TpmIoWriter.Flush();
                }
            }

            if (ChainedCallbacks != null)
            {
                ChainedCallbacks.PostCallback(inBuf, outBuf);
            }
        } // ICommandCallbacks.PostCallback
Esempio n. 17
0
        void TestAutomaticAuth(Tpm2 tpm, TestContext testCtx)
        {
            TpmHandle hPrim = Substrate.LoadRsaPrimary(tpm);

            // Make an RSA encryption key.
            var    decScheme = new SchemeOaep(Substrate.Random(TpmCfg.HashAlgs));
            var    sigScheme = new SchemeRsassa(Substrate.Random(TpmCfg.HashAlgs));
            ushort keyLength = Substrate.RandomRsaKeySize(decScheme.hashAlg);
            var    inPub     = new TpmPublic(Substrate.Random(TpmCfg.HashAlgs),
                                             ObjectAttr.Decrypt | ObjectAttr.Sign
                                             | ObjectAttr.FixedParent | ObjectAttr.FixedTPM
                                             | ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin,
                                             null,
                                             new RsaParms(new SymDefObject(), null, keyLength, 0),
                                             new Tpm2bPublicKeyRsa());

            TpmPublic  keyPublic;
            TpmPrivate keyPrivate = Substrate.Create(tpm, hPrim, inPub, out keyPublic);

            TpmHandle keyHandle = null;

            tpm._Behavior.Strict = true;
            try
            {
                // No auth session is added automatically when TPM object is in strict mode.
                tpm._ExpectError(TpmRc.AuthMissing)
                .Load(hPrim, keyPrivate, keyPublic);

                // Now explicitly request an auth session of appropriate type
                keyHandle = tpm[Auth.Default].Load(hPrim, keyPrivate, keyPublic);
            }
            finally
            {
                tpm._Behavior.Strict = false;
            }

            byte[] message = Substrate.RandBytes(1, TpmHelper.MaxOaepMsgSize(keyLength, decScheme.hashAlg));

            byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, null);

            // An auth session is added automatically when TPM object is not in strict mode.
            byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, null);

            TpmAlgId auditHashAlg = Substrate.Random(TpmCfg.HashAlgs);

            byte[] nonceTpm;

            // AuthSession object can be built from session handle concatenated, if necessary,
            // with session flags and unencrypted salt value (not used in this example).
            AuthSession auditSess = tpm.StartAuthSession(
                TpmRh.Null,                              // no salt
                TpmRh.Null,                              // no bind object
                Substrate.RandomNonce(auditHashAlg),     // nonceCaller
                null,                                    // no salt
                TpmSe.Hmac,                              // session type
                new SymDef(),                            // no encryption/decryption
                auditHashAlg,                            // authHash
                out nonceTpm)
                                    + (SessionAttr.ContinueSession | SessionAttr.Audit);

            /*
             * Alternatively one of the StartAuthSessionEx helpers can be used)
             * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, auditHashAlg, null,
             *                                                SessionAttr.ContinueSession | SessionAttr.Audit);
             */

            // TSS-specific call to verify TPM auditing correctness.
            tpm._SetCommandAuditAlgorithm(auditHashAlg);

            // Appropriate auth value is added automatically into the provided session
            byte[] decrypted2 = tpm[auditSess]._Audit()
                                .RsaDecrypt(keyHandle, encrypted, decScheme, null);

            ISignatureUnion sig;
            Attest          attest;

            // A session is added automatically to authorize TpmRh.Endorsement usage.
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess,
                                               null, new NullSigScheme(), out sig);

            // But if the corresponding auth value stored in the Tpm2 object is invalid, ...
            AuthValue endorsementAuth = tpm.EndorsementAuth;

            tpm.EndorsementAuth = Globs.ByteArray(16, 0xde);
            // ... the command will fail
            tpm._ExpectError(TpmRc.BadAuth)
            .GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess,
                                   null, new NullSigScheme(), out sig);
            // Restore correct auth value.
            tpm.EndorsementAuth = endorsementAuth;

            // Verify that both decryption and auditing worked correctly.
            SessionAuditInfo info = (SessionAuditInfo)attest.attested;

            byte[] auditDigest = tpm._GetAuditHash();
            testCtx.AssertEqual("AuditSessionDigest", info.sessionDigest, auditDigest);
            testCtx.AssertEqual("Decryption", decrypted1, decrypted2);

            // Change auth value of the decryption key.
            TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, hPrim,
                                                            Substrate.RandomAuth(keyPublic.nameAlg));
            TpmHandle newKeyHandle = tpm.Load(hPrim, newKeyPrivate, keyPublic);

            auditSess.Attrs &= ~SessionAttr.AuditExclusive;
            // Correct auth value (corresponding to newKeyHandle, and different from
            // the one used for keyHandle) will be added to auditSess.
            decrypted1 = tpm[auditSess]._Audit().RsaDecrypt(newKeyHandle, encrypted, decScheme, null);

            // And now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle).
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess,
                                               null, sigScheme, out sig);
            bool sigOk = keyPublic.VerifySignatureOverData(
                Marshaller.GetTpmRepresentation(attest), sig);

            testCtx.Assert("AuditSessionSignatute.1", sigOk);

            // Here the first session is generated based on session type indicator
            // (Auth.Pw), and the second one is added automatically.
            attest = tpm[Auth.Pw].GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess,
                                                        null, sigScheme, out sig);

            // Verify that auditing worked correctly.
            sigOk = keyPublic.VerifySignatureOverData(
                Marshaller.GetTpmRepresentation(attest), sig);
            testCtx.Assert("AuditSessionSignatute.2", sigOk);

            tpm.FlushContext(newKeyHandle);
            tpm.FlushContext(auditSess);

            if (!TestCfg.HasTRM)
            {
                // Deplete TPM's active session storage
                List <AuthSession> landfill = new List <AuthSession>();

                for (;;)
                {
                    tpm._AllowErrors();
                    AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, Substrate.Random(TpmCfg.HashAlgs),
                                                           SessionAttr.ContinueSession);
                    if (!tpm._LastCommandSucceeded())
                    {
                        break;
                    }
                    landfill.Add(s);
                }

                // Check if session type indicators are processed correctly
                tpm[Auth.Hmac]._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, null, null);
                tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, null, null);

                // Check if default session type defined by the TPM device is processed correctly
                bool needHmac = tpm._GetUnderlyingDevice().NeedsHMAC;

                tpm._GetUnderlyingDevice().NeedsHMAC = true;
                tpm._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, null, null);
                tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, null, null);

                tpm._GetUnderlyingDevice().NeedsHMAC = false;
                tpm.RsaDecrypt(keyHandle, encrypted, null, null);
                tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, null, null);

                tpm._GetUnderlyingDevice().NeedsHMAC = needHmac;

                landfill.ForEach(s => tpm.FlushContext(s));
            }
            tpm.FlushContext(keyHandle);
        } // TestAutomaticAuth
Esempio n. 18
0
        internal void DoIt(_AcAp.Document doc, string rbName, string fgLayer)
        {
            log.Debug("--------------------------");

            _FlaechenGrenzen.Clear();
            _Raumbloecke.Clear();

            var _AreaEngine = new AreaEngine();

            _AcGe.Matrix3d ucs = _AcGe.Matrix3d.Identity;
            try
            {
                ucs = doc.Editor.CurrentUserCoordinateSystem;
                doc.Editor.CurrentUserCoordinateSystem = _AcGe.Matrix3d.Identity;

                if (!string.IsNullOrEmpty(rbName))
                {
                    _RaumblockName = rbName;
                }
                if (!string.IsNullOrEmpty(fgLayer))
                {
                    _FgLayer = fgLayer;
                }

                _AreaEngine.SelectFgAndRb(_FlaechenGrenzen, _Raumbloecke, _FgLayer, _RaumblockName);

                if (_FlaechenGrenzen.Count == 0)
                {
                    return;
                }

                // todo: läuft nicht synchron - wird dzt in lisp ausgeführt
                //Globs.SetWorldUCS();

                ZoomToFlaechenGrenzen();

                // init div
                int fehlerKeinRb     = 0;
                int fehlerMehrRb     = 0;
                int fehlerWertFalsch = 0;

                _AcDb.Database           db  = doc.Database;
                _AcEd.Editor             ed  = doc.Editor;
                _AcDb.TransactionManager tm  = db.TransactionManager;
                _AcDb.Transaction        myT = tm.StartTransaction();
                try
                {
                    _AcGe.Point2d lu = new _AcGe.Point2d();
                    _AcGe.Point2d ro = new _AcGe.Point2d();

                    for (int i = 0; i < _FlaechenGrenzen.Count; i++)
                    {
                        log.Debug("--------------------------");

                        double         sumAF = 0;
                        int            rbInd = -1;
                        _AcDb.ObjectId elFG  = _FlaechenGrenzen[i];
                        log.DebugFormat("Flächengrenze {0}", elFG.Handle.ToString());

                        _AcDb.Extents3d ext    = GetExtents(tm, elFG);
                        _AcGe.Point3d   minExt = new _AcGe.Point3d(ext.MinPoint.X - ABSTANDTEXT, ext.MinPoint.Y - ABSTANDTEXT, ext.MinPoint.Z);
                        _AcGe.Point3d   maxExt = new _AcGe.Point3d(ext.MaxPoint.X + ABSTANDTEXT, ext.MaxPoint.Y + ABSTANDTEXT, ext.MaxPoint.Z);

                        List <_AcDb.ObjectId> rbsToIgnoreCol = GetFgAnz(minExt, maxExt, elFG);
                        if (rbsToIgnoreCol.Count > 0)
                        {
                            string handles = string.Join(",", rbsToIgnoreCol.Select(x => x.Handle.ToString()).ToArray());
                            log.DebugFormat("Zu ignorierende Raumblöcke: {0}", handles);
                        }

                        //    'raumbloecke holen
                        List <_AcDb.ObjectId> ssRB = selRB(minExt, maxExt);
                        if (ssRB.Count > 0)
                        {
                            string handles = string.Join(",", ssRB.Select(x => x.Handle.ToString()).ToArray());
                            log.DebugFormat("Raumblöcke: {0}", handles);
                        }


                        int rbAnz = 0;
                        //    'raumbloecke pruefen
                        for (int rbCnt = 0; rbCnt < ssRB.Count; rbCnt++)
                        {
                            _AcDb.ObjectId rbBlock2 = ssRB[rbCnt];

                            //      ' ignore rbs
                            _AcDb.ObjectId found = rbsToIgnoreCol.FirstOrDefault(x => x.Equals(rbBlock2));
                            if (found != default(_AcDb.ObjectId))
                            {
                                continue;
                            }

                            using (_AcDb.DBObject dbObj = tm.GetObject(rbBlock2, _AcDb.OpenMode.ForRead, false))
                            {
                                _AcGe.Point3d rbEp = ((_AcDb.BlockReference)dbObj).Position;

                                using (_AcDb.Entity elFGEnt = (_AcDb.Entity)tm.GetObject(elFG, _AcDb.OpenMode.ForRead, false))
                                {
                                    if (AreaEngine.InPoly(rbEp, elFGEnt))
                                    {
                                        log.DebugFormat("Raumblock {0} ist innerhalb der Flächengrenze.", rbBlock2.Handle.ToString());

                                        if (_Raumbloecke.Contains(rbBlock2))
                                        {
                                            _Raumbloecke.Remove(rbBlock2);
                                        }
                                        rbAnz++;
                                        rbInd = rbCnt;
                                    }
                                    else
                                    {
                                        log.DebugFormat("Außen liegender Raumblock {0} wird ignoriert.", rbBlock2.Handle.ToString());
                                    }
                                }
                            }
                        }


                        if (rbAnz < 1)
                        {
                            log.WarnFormat("Kein Raumblock in Flächengrenze {0}!", elFG.Handle.ToString());
                            //FehlerLineOrHatchPoly(elFG, _InvalidNrRb, 255, 0, 0, tm, Globs.GetLabelPoint(elFG));
                            fehlerKeinRb++;
                        }
                        else if (rbAnz > 1)
                        {
                            log.WarnFormat("Mehr als ein Raumblock in Flächengrenze {0}!", elFG.Handle.ToString());
                            //FehlerLineOrHatchPoly(elFG, _InvalidNrRb, 255, 0, 0, tm, Globs.GetLabelPoint(elFG));
                            fehlerMehrRb++;
                        }
                        else
                        {
                            using (var tr = doc.TransactionManager.StartTransaction())
                            {
                                var pt = Globs.GetLabelPoint(elFG);
                                if (pt.HasValue)
                                {
                                    var rblock = tr.GetObject(ssRB[rbInd], _AcDb.OpenMode.ForWrite) as _AcDb.BlockReference;

                                    var pos = rblock.GetCenter();
                                    if (!pos.HasValue)
                                    {
                                        pos = rblock.Position;
                                    }
                                    _AcGe.Vector3d acVec3d = pos.Value.GetVectorTo(pt.Value);
                                    rblock.TransformBy(_AcGe.Matrix3d.Displacement(acVec3d));
                                    ed.WriteMessage("\nCentroid is {0}", pt);
                                }
                                else
                                {
                                    var    poly = tr.GetObject(elFG, _AcDb.OpenMode.ForRead) as _AcDb.Polyline;
                                    string msg  = string.Format(CultureInfo.CurrentCulture, "\nFläche {0}. Centroid liegt außerhalb.", poly.Handle.ToString());
                                    ed.WriteMessage(msg);
                                    log.Warn(msg);
                                }

                                tr.Commit();
                            }
                        }
                    }

                    //if (_Raumbloecke.Count > 0)
                    //{
                    //    List<object> insPoints = new List<object>();
                    //    for (int i = 0; i < _Raumbloecke.Count; i++)
                    //    {
                    //        _AcIntCom.AcadBlockReference rbBlock = (_AcIntCom.AcadBlockReference)Globs.ObjectIdToAcadEntity(_Raumbloecke[i], tm);
                    //        insPoints.Add(rbBlock.InsertionPoint);
                    //    }

                    //    _AcCm.Color col = _AcCm.Color.FromRgb((byte)0, (byte)255, (byte)0);

                    //    Plan2Ext.Globs.InsertFehlerLines(insPoints, _LooseBlockLayer, 50, Math.PI * 1.25, col);

                    //}



                    if (fehlerKeinRb > 0 || fehlerMehrRb > 0 || fehlerWertFalsch > 0 || _Raumbloecke.Count > 0)
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, "Räume ohne Raumblock: {0}\nRäume mit mehr als einem Raumblock: {1}\nRäume mit falschem Wert in Raumblock: {2}\nRaumblöcke ohne entsprechende Flächengrenzen: {3}", fehlerKeinRb, fehlerMehrRb, fehlerWertFalsch, _Raumbloecke.Count);
                        log.Debug(msg);
                        _AcAp.Application.ShowAlertDialog(msg);
                    }

                    //If wucs = 0 Then
                    //    ThisDrawing.SendCommand "(command ""_.UCS"" ""_P"") "
                    //End If

                    myT.Commit();
                }
                finally
                {
                    myT.Dispose();
                }
            }
            finally
            {
                doc.Editor.CurrentUserCoordinateSystem = ucs;
            }
        }
Esempio n. 19
0
 string ReadLine(string fileName, int lineNum)
 {
     string[] t = Globs.ReadAllLines(fileName);
     return(t[lineNum - 1]);
 }
Esempio n. 20
0
 void WriteInt(int x, NetworkStream s)
 {
     s.Write(Globs.HostToNet(x), 0, 4);
 }
Esempio n. 21
0
        // This routine checks that the observed test behavior matches the attributes.
        // It is called during a -validate pass on a full TPM simulator
        internal void ValidateTestAttributeCollection(MethodInfo test, Tpm2 tpm)
        {
            var attr = Globs.GetAttr <TestAttribute>(test);

            // check that the cumulative attributes match the claimed attributes
            if (attr.SpecialNeeds.HasFlag(Special.NotThreadSafe) == TestIsThreadSafe)
            {
                string s = "<Benign>";
                if (!TestIsThreadSafe)
                {
                    // It is safe to say you are not thread safe if you are not (and
                    // there are commands that the test harness does not understand
                    // that might lead you to be not thread safe
                    s = "<Critical - must be fixed>";
                    SetColorCritical(true);
                }
                else
                {
                    SetColorCritical(false);
                }
                Logger.WriteErrorToLog("\nThread safety attribute does not match " +
                                       "observed behavior for {0} {1}", test.Name, s);
            }

            bool PowerCycleWasIssued = ((TpmPassThroughDevice)tpm._GetUnderlyingDevice())
                                       .GetPowerCycleDirtyBit();

            if (attr.SpecialNeeds.HasFlag(Special.PowerControl) != PowerCycleWasIssued)
            {
                SetColorCritical(PowerCycleWasIssued);
                Logger.WriteErrorToLog("\nPower-cycle attribute does not match observed behavior");
            }
            if ((attr.CommProfile == Profile.MinTPM) != TestWithinMinTpmProfile)
            {
                SetColorCritical(attr.CommProfile == Profile.MinTPM);
                string profile = attr.CommProfile.ToString();
                Logger.WriteErrorToLog("\nClaimed profile {0} but this does not match " +
                                       "observed behavior for {1}", profile, test.Name);
            }
            // change privUsed and privStated into a number so that we can compare
            // bigger numbers are more privileged
            int privUsed, privStated;

            switch (MaximumPrivilege)
            {
            case NecessaryPrivilege.User: privUsed = 0; break;

            case NecessaryPrivilege.Admin: privUsed = 1; break;

            case NecessaryPrivilege.Special: privUsed = 2; break;

            case NecessaryPrivilege.Debug: privUsed = 3; break;

            default: throw new Exception("tester fault");
            }
            switch (attr.Privileges)
            {
            case Privileges.StandardUser:  privStated = 0; break;

            case Privileges.Admin: privStated = 1; break;

            case Privileges.Special: privStated = 3; break;

            default: throw new Exception("badly attributed test.  Need a stated privilege");
            }

            bool maxPrivOk       = (privStated >= privUsed);
            bool privilegesMatch = privUsed == privStated || (privStated == 3 && privUsed == 2);

            /*
             * switch (MaximumPrivilege)
             * {
             *  case NecessaryPrivilege.User:
             *      if (attr.Privileges != PrivilegesNeeded.StandardUser) maxPrivOk = false;
             *      break;
             *  case NecessaryPrivilege.Admin:
             *      if (attr.Privileges != PrivilegesNeeded.Admin) maxPrivOk = false;
             *      break;
             *  case NecessaryPrivilege.Special:
             *      if (attr.Privileges != PrivilegesNeeded.Special) maxPrivOk = false;
             *      break;
             *  default:
             *      throw new Exception("");
             * }
             * // maxPriv is only defined for commands within the MinTPM profile
             */
            if (!privilegesMatch)
            {
                SetColorCritical(!maxPrivOk);
                Logger.WriteErrorToLog("\nPrivilege used is {0} but stated {1} for test {2}",
                                       MaximumPrivilege, attr.Privileges, test.Name);
                if (!maxPrivOk)
                {
                    Logger.WriteErrorToLog("critical - must fix.");
                }
            }
            if (TestUsesPlatformAuth)
            {
                // not allowed for
                if (attr.CommProfile == Profile.MinTPM)
                {
                    SetColorCritical(true);
                    string profile = attr.CommProfile.ToString();
                    Logger.WriteErrorToLog("\nClaimed profile {0} but used PlatformAuth: {1}",
                                           profile, test.Name);
                }
            }
            Console.ResetColor();
        }
Esempio n. 22
0
        int ReadInt(NetworkStream s)
        {
            int val = Globs.NetToHost4(Read(4, s));

            return(val);
        }
Esempio n. 23
0
 public void AssertNotEqual(string label, byte[] arr1, byte[] arr2,
                            params Object[] parms)
 {
     Assert(label, !Globs.ArraysAreEqual(arr1, arr2), Gather(arr1, arr2, parms));
 }
Esempio n. 24
0
        /// <summary>
        /// The callback to sign the TpmPolicySignature challenge from the TPM.
        /// </summary>
        /// <param name="policyTree">The policy tree to check.</param>
        /// <param name="ace">The policy element (TpmPolicySignature) to evaluate.</param>
        /// <param name="nonceTpm">The nonce from the TPM.</param>
        /// <returns>Signature of the nonce.</returns>
        public static ISignatureUnion SignerCallback(PolicyTree policyTree, TpmPolicySigned ace,
                                                     byte[] nonceTpm, out TpmPublic verificationKey)
        {
            //
            // This function checks the parameters of the associated TpmPolicySigned
            // ACE, and if they are those expected the TPM challenge is signed.
            // Note that policy expressions are often obtained from untrustworthy
            // sources, so it is important for key-holders to check what they
            // are bing asked to do before signing anything.
            //

            //
            // The policy just contains the name of the signature verification key, however the
            // TPM needs the actual public key to verify the signature.  Check that the name
            // matches, and if it does return the public key.
            //
            byte[] expectedName = _publicSigningKey.GetPublicParms().GetName();
            if (!expectedName.SequenceEqual(ace.AuthObjectName))
            {
                throw new Exception("Unexpected name in policy.");
            }
            verificationKey = _publicSigningKey.GetPublicParms();

            //
            // Check that the key is the one that we expect
            //
            if (ace.NodeId != "Signing Key 1")
            {
                throw new Exception("Unrecognized key");
            }


            //
            // Check that nonceTom is not null (otherwise anything we sign can
            // be used for any session).
            //
            if (Globs.IsEmpty(nonceTpm))
            {
                throw new Exception("Sign challenges with expiration time need nonce.");
            }

            //
            // Check PolicyRef and cpHash are what we want to sign
            //
            if (!Globs.IsEmpty(ace.CpHash))
            {
                throw new Exception("I only sign null-cpHash");
            }

            if (!ace.PolicyRef.SequenceEqual(new byte[] { 1, 2, 3, 4 }))
            {
                throw new Exception("Incorrect PolicyRef");
            }

            //
            // And finally check that the expiration is set correctly. Check for
            // positive values (simple signing policy) and negative values (sining
            // policy with ticket).
            //
            if (ace.ExpirationTime != _expectedExpirationTime)
            {
                throw new Exception("Unexpected expiration time");
            }

            //
            // Everything is OK, so get a formatted bloc containing the challenge
            // data and then sign it.
            //
            byte[] dataToSign = PolicyTree.PackDataToSign(ace.ExpirationTime, nonceTpm,
                                                          ace.CpHash, ace.PolicyRef);
            return(_publicSigningKey.Sign(dataToSign));
        }
Esempio n. 25
0
        private void ZoomToFlaechenGrenzen()
        {
            log.DebugFormat(CultureInfo.CurrentCulture, "Zoom auf Flächengrenzen");
            if (_FlaechenGrenzen.Count == 0)
            {
                return;
            }

            double MinX, MinY, MaxX, MaxY;

            _AcAp.Document           doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcDb.Database           db  = doc.Database;
            _AcEd.Editor             ed  = doc.Editor;
            _AcDb.TransactionManager tm  = db.TransactionManager;
            _AcDb.Transaction        myT = tm.StartTransaction();
            try
            {
                _AcDb.Extents3d ext = GetExtents(tm, _FlaechenGrenzen[0]);
                MinX = ext.MinPoint.X;
                MinY = ext.MinPoint.Y;
                MaxX = ext.MaxPoint.X;
                MaxY = ext.MaxPoint.Y;

                for (int i = 1; i < _FlaechenGrenzen.Count; i++)
                {
                    _AcDb.ObjectId oid = _FlaechenGrenzen[i];
                    ext = GetExtents(tm, oid);
                    if (ext.MinPoint.X < MinX)
                    {
                        MinX = ext.MinPoint.X;
                    }
                    if (ext.MinPoint.Y < MinY)
                    {
                        MinY = ext.MinPoint.Y;
                    }
                    if (ext.MaxPoint.X > MaxX)
                    {
                        MaxX = ext.MaxPoint.X;
                    }
                    if (ext.MaxPoint.Y > MaxY)
                    {
                        MaxY = ext.MaxPoint.Y;
                    }
                }


                //Globs.Zoom( new Point3d(MinX, MinY, 0.0), new Point3d(MaxX, MaxY, 0.0),new Point3d(), 1.0);
                //Globs.ZoomWin3(ed, new Point3d(MinX, MinY, 0.0), new Point3d(MaxX, MaxY, 0.0));
                //Globs.ZoomWin2(ed, new Point3d(MinX, MinY, 0.0), new Point3d(MaxX, MaxY, 0.0));

                myT.Commit();
            }
            finally
            {
                myT.Dispose();
            }

            // Rauszoomen, sonst werden Blöcken nicht gefunden, die außerhalb der Flächengrenzen liegen.
            MinX -= ABSTANDTEXT;
            MinY -= ABSTANDTEXT;
            MaxX += ABSTANDTEXT;
            MaxY += ABSTANDTEXT;

            Globs.Zoom(new _AcGe.Point3d(MinX, MinY, 0.0), new _AcGe.Point3d(MaxX, MaxY, 0.0), new _AcGe.Point3d(), 1.0);
        }
Esempio n. 26
0
        } // GenerateTestCasesTable

        internal void GenerateReport(string fileName)
        {
            TimeSpan testTimeSpan = DateTime.Now - TestSessStartTime;

            StringBuilder  sb = new StringBuilder();
            StringWriter   sw = new System.IO.StringWriter(sb);
            HtmlTextWriter w  = new HtmlTextWriter(sw);

            w.RenderBeginTag(HtmlTextWriterTag.Body);

            WriteLine(w, "TPM Test Report", HtmlTextWriterTag.H1);
            WriteLine(w, "Start Time: " + TestSessStartTime.ToString("F"));
            WriteLine(w, "Duration: " + testTimeSpan.TotalMinutes.ToString("F2") + " min");

            bool failed   = CumulativeFailures.Count != 0;
            bool aborted  = AbortedTests.Count != 0;
            bool warnings = CumulativeWarnings.Count != 0;

            string title;

            if (failed)
            {
                title = "Some tests FAILED"
                        + (aborted ? " or were ABORTED" : "")
                        + (warnings ? " and there were WARNINGS" : "");
            }
            else
            {
                title = "All Tests PASSED"
                        + (warnings ? " with WARNINGS" : "")
                        + (aborted ? (warnings ? " and" : " but") + " some were ABORTED" : "");
            }
            WriteLine(w, title, HtmlTextWriterTag.H1);

            WriteLine(w, "Total Substrate.Assertions Checked = " + TotalNumAsserts);

            // ================  FAILING CASES SECTION ==========================
            GenerateTestCasesTable(CumulativeFailures, "Failing Cases", w);

            // ================  ABORTED CASES SECTION ==========================
            if (AbortedTests.Count != 0)
            {
                WriteLine(w, "Aborted Cases", HtmlTextWriterTag.H2);
                WriteLine(w, "Tests aborted because of commands not implemented by " +
                          "the target TPM, or blocked by OS.");

                BeginTable(w, "Test Case", "Abort Reason");
                foreach (var item in AbortedTests)
                {
                    WriteTableRow(w, item.Key, GetAbortReasonMessage(item.Value));
                }
                EndTable(w); // table
            }

            // ================  WARNINGS SECTION ==========================
            GenerateTestCasesTable(CumulativeWarnings, "Warnings", w);

            // ================  COMMAND STATS SECTION ==========================
            WriteLine(w, "Command Statistics", HtmlTextWriterTag.H2);
            WriteLine(w, "Total TPM Commands Executed = " + TotalNumCommands);

            BeginTable(w, "Command Code", "Successes", "Failures",
                       "Average<br>Success<br>Time, ms", "Average<br>Failure<br>Time, ms",
                       "Error Codes", "Calling Tests");

            var sortedStats = CumulativeCmdStats.OrderBy(item => item.Key.ToString()); // item.Value.NumSuccess

            //var sortedStats = CumulativeCmdStats;
            foreach (var item in sortedStats)
            {
                CommandStats stat           = item.Value;
                string       avgSuccessTime = stat.NumSuccess == 0 ? "-" : String.Format("{0:F1}",
                                                                                         stat.SuccessExecutionTime.TotalMilliseconds / stat.NumSuccess);
                string avgFailureTime = stat.NumFailures == 0 ? "-" : String.Format("{0:F2}",
                                                                                    stat.FailureExecutionTime.TotalMilliseconds / stat.NumFailures);
                WriteTableRow(w, item.Key, stat.NumSuccess, stat.NumFailures,
                              avgSuccessTime, avgFailureTime,
                              Globs.ToString(stat.FailureResponses, ", ", "-"),
                              Globs.ToString(stat.CallerTests, ", ", "-"));
            }
            EndTable(w);

            // commands not executed -
            List <TpmCc> notExecuted = new List <TpmCc>();

            foreach (var c in CommandInformation.Info)
            {
                int num = sortedStats.Sum(y => (y.Key == c.CommandCode) ? 1 : 0);
                if (num == 0)
                {
                    Debug.WriteLine("Not executed:" + c.CommandCode.ToString());
                }
            }

            // ================  TEST ROUTINE STATS SECTION ==========================
            WriteLine(w, "Test Routine Statistics", HtmlTextWriterTag.H2);

            int totalTestRoutineCount = this.TestRoutinesStats.Sum(item =>
                                                                   item.Value.NumAborted + item.Value.NumFailed + item.Value.NumSuccess);

            WriteLine(w, "Total Test Routines Executed = " + totalTestRoutineCount);

            BeginTable(w, "Test Name", "Succeeded", "Failed", "Aborted", "Average<BR>Time, s");

            var sortedTestStats = TestRoutinesStats.OrderBy(item => item.Key.ToString());

            foreach (var item in sortedTestStats)
            {
                TestStats stat = item.Value;
                int       n    = stat.NumSuccess + stat.NumFailed + stat.NumAborted;
                if (n == 0)
                {
                    continue;
                }
                string avgTime = String.Format("{0:F2}",
                                               (double)stat.TotalExecutionTime / n / 1000);
                WriteTableRow(w, item.Key, stat.NumSuccess, stat.NumFailed,
                              stat.NumAborted, avgTime);
            }
            EndTable(w);

            w.RenderEndTag(); // Body
            File.WriteAllText(fileName, sb.ToString());
        }
Esempio n. 27
0
        internal void GenerateWLKReport(ref int Run, ref int Fail, ref int Success, bool PassFailedTests)
        {
            foreach (TestCaseInfo c in CumulativeFailures)
            {
                string parmsText = "";

                // >>> write parms
                if (c.Parms != null)
                {
                    foreach (Object o in c.Parms)
                    {
                        if (o is TestCaseInfo)
                        {
                            // Formerly this parameter contained an exception object,
                            // information from which is now encapsulated in 'c'.
                            continue;
                        }
                        else if (o is Enum)
                        {
                            parmsText += Enum.GetName(o.GetType(), o) + " : ";

                            bool  first  = true;
                            Enum  e      = o as Enum;
                            Array values = Enum.GetValues(o.GetType());

                            foreach (Enum v in values)
                            {
                                if (e.HasFlag(v))
                                {
                                    if (!first)
                                    {
                                        parmsText += " | ";
                                    }
                                    else
                                    {
                                        first = false;
                                    }
                                    parmsText += Enum.GetName(o.GetType(), v);
                                }
                            }
                        }
                        else if (o is byte[])
                        {
                            parmsText += Globs.HexFromByteArray((byte[])o);
                        }
                        else
                        {
                            parmsText += o.ToString();
                        }
                        parmsText += "<p>";
                    }
                }
                else
                {
                    parmsText = "<br>";
                }

                string details = c.Message + "\n"
                                 + c.Location + "\n"
                                 + "Parameters:\n" + parmsText
                                 + (string.IsNullOrEmpty(c.RngSeed) ? ""
                                    : "To reproduce use option: -seed " + c.RngSeed + "\n");
                details.Replace("\r", "");

                string errorText = c.TestCase.Replace(":", " : ") + ";\n" + details;
                // c.StackTrace.Replace("\r", "");

                WriteToWLKLog(errorText, TestResult.Failed, PassFailedTests);
            }

            // ================  ABORTED CASES SECTION ==========================
            foreach (var item in AbortedTests)
            {
                string errorText = "TestCaseInfo:" + item.Key + " aborted because: "
                                   + GetAbortReasonMessage(item.Value);
                if (item.Value.reason == AbortReason.BlockedCommand)
                {
                    WriteToWLKLog(errorText, TestResult.NotRun, PassFailedTests);
                }
                else
                {
                    WriteToWLKLog(errorText, TestResult.Failed, PassFailedTests);
                }
            }

            // ================  COMMAND STATS SECTION ==========================
            Log.Comment(string.Format("Total TPM command count: {0}", TotalNumCommands));

            string successfulCommands = "Commands executed: ";
            var    sortedStats        = CumulativeCmdStats.OrderBy(item => item.Key.ToString());

            //var sortedStats = CumulativeCmdStats;
            foreach (var item in sortedStats)
            {
                CommandStats stat = item.Value;
                successfulCommands += item.Key + " (" + stat.NumSuccess + ") ";
            }
            Log.Comment(successfulCommands);
            WriteToLog(successfulCommands);

            // commands not executed -
            List <TpmCc> notExecuted = new List <TpmCc>();

            foreach (var c in CommandInformation.Info)
            {
                int num = sortedStats.Sum(y => (y.Key == c.CommandCode) ? 1 : 0);
                if (num == 0 && TestCategorizer.CommandDefinedForMinTpm(c.CommandCode))
                {
                    Log.Comment("Command " + c.CommandCode + " not executed.");
                }
            }

            // ================  TEST ROUTINE STATS SECTION ==========================
            int totalTestRoutineCount = this.TestRoutinesStats.Sum(item =>
                                                                   item.Value.NumAborted + item.Value.NumFailed + item.Value.NumSuccess);
            var sortedTestStats = TestRoutinesStats.OrderByDescending(item => item.Value.NumFailed);

            foreach (var item in sortedTestStats)
            {
                if (item.Value.NumFailed == 0)
                {
                    break;  // no more failures
                }
                WriteToWLKLog(string.Format("{0} failed.", item.Key),
                              TestResult.Failed, PassFailedTests);
                Fail++;
            }
            sortedTestStats = TestRoutinesStats.OrderByDescending(item => item.Value.NumSuccess);
            foreach (var item in sortedTestStats)
            {
                if (item.Value.NumSuccess == 0)
                {
                    break;  // no more failures
                }
                Verify.IsTrue(true, item.Key);
                WriteToLog("{0} passed.", item.Key);
                Success++;
            }
            foreach (var item in sortedTestStats)
            {
                TestStats stat = item.Value;
                if (stat.NumSuccess == 0 && stat.NumFailed == 0)
                {
                    Log.Result(TestResult.NotRun, string.Format("{0} not run.", item.Key));
                    Run++;
                }
            }
        }
Esempio n. 28
0
 public List <string> GetTestListFromAttrs(Func <TestAttribute, bool> fits)
 {
     return(Globs.ConvertAll(Target.AllTests.Where(
                                 item => fits(Globs.GetAttr <TestAttribute>(item))),
                             item => item.Name));
 }
Esempio n. 29
0
        // Returns the ratio of a TPM clock second to one system time second
        public static double MeasureClockRate(Tpm2 tpm)
        {
            const int MaxIter           = 20;
            int       NumSamplesPerIter = 5;
            int       N = NumSamplesPerIter,
                      L = 0;

            double[] tpmTimes    = null;
            double[] sysTimes    = null;
            double[] newTpmTimes = new double[N];
            double[] newSysTimes = new double[N];
            int      iter        = 0;

            double stdDevSys = 0,
                   meanSys = 0,
                   stdDevTpm = 0,
                   meanTpm = 0;
            int    n = 0;
            double sysTime = 0, tpmTime = 0;

            do
            {
                tpmTimes = newTpmTimes;
                sysTimes = newSysTimes;

                TimeInfo tpmStart = null;
                DateTime sysStart = DateTime.MinValue;

                for (int i = L; i <= N; i++)
                {
                    TimeInfo tpmStop = tpm.ReadClock();
                    DateTime sysStop = DateTime.Now;
                    if (tpmStart != null)
                    {
                        tpmTimes[i - 1] = tpmStop.time - tpmStart.time;
                        sysTimes[i - 1] = (sysStop - sysStart).TotalMilliseconds;
                    }
                    tpmStart = tpmStop;
                    sysStart = sysStop;
                    Thread.Sleep(600);
                }

                // Eliminate outliers that may be caused by the current thread having
                // been preempted at a "wrong" point causing the measured rate distortion.
                meanSys = meanTpm = stdDevSys = stdDevTpm = sysTime = tpmTime = 0;
                for (int i = 0; i < N; i++)
                {
                    meanSys += sysTimes[i];
                    meanTpm += tpmTimes[i];
                }
                meanSys /= N;
                meanTpm /= N;

                for (int i = 0; i < N; i++)
                {
                    double d = (sysTimes[i] - meanSys);
                    stdDevSys += d * d;
                    d          = (tpmTimes[i] - meanTpm);
                    stdDevTpm += d * d;
                }
                stdDevSys = Math.Sqrt(stdDevSys / N);
                stdDevTpm = Math.Sqrt(stdDevTpm / N);

                bool imprecise = stdDevSys / meanSys > 0.03 || stdDevTpm / meanTpm > 0.03;
                if (imprecise)
                {
                    newTpmTimes = new double[N + NumSamplesPerIter];
                    newSysTimes = new double[N + NumSamplesPerIter];
                }

                n = 0;
                for (int i = 0; i < N; i++)
                {
                    if (Math.Abs(sysTimes[i] - meanSys) < 2 * stdDevSys &&
                        Math.Abs(tpmTimes[i] - meanTpm) < 2 * stdDevTpm)
                    {
                        sysTime += sysTimes[i];
                        tpmTime += tpmTimes[i];
                        if (imprecise)
                        {
                            newSysTimes[n] = sysTimes[i];
                            newTpmTimes[n] = tpmTimes[i];
                        }
                        ++n;
                    }
                    //else Console.Write("Dropped[{0}] = {1} ", i, sysTimes[i]);
                }
                if (!imprecise && n > 2)
                {
                    break;
                }
                L = n;
                N = L + NumSamplesPerIter;
            } while (++iter < MaxIter);

            if (iter == MaxIter)
            {
                Globs.Throw("The system is likely overloaded. Cannot do reliable time measurements.");
            }

            //Console.WriteLine("ITER {0}, MEAN {1:F0}->{2:F0}, SD {3:F1}; Good {4}; RATE {5:F2}",
            //                  iter+1, meanSys, sysTime / n, stdDevSys, n, tpmTime / sysTime);
            return(tpmTime / sysTime);
        } // MeasureClockRate()
Esempio n. 30
0
 void WriteVarArray(byte[] x, NetworkStream s)
 {
     Write(Globs.HostToNet(x.Length), s);
     Write(x, s);
 }