Home > Articles > Cisco Network Technology > General Networking > Security in Tcl Scripts for Cisco IOS

Security in Tcl Scripts for Cisco IOS

  • Sample Chapter is provided courtesy of Cisco Press.
  • Date: Aug 10, 2010.

Chapter Description

This chapter provides an introduction to PKI infrastructure and goes on to cover the use of digital signatures to sign a Tcl script, a scenario for Tcl script-failure, and scaling Tcl script distribution.

From the Book

TcL Scripting for Cisco IOS

TcL Scripting for Cisco IOS

$67.99

Using Digital Signatures to Sign a Tcl Script

Two prerequisites must be met to sign a Tcl script:

  • A digital certificate must be made available on the router that will perform the signature check of the Tcl script. The digital certificate is stored in the IOS running-configuration and may also be saved in the nonvolatile random-access memory (NVRAM) of the router.
  • The Tcl script must have been signed with the private key that matches the public key available in the digital certificate. The signature is provided in a special format and is in plain text directly after the Tcl commands in the script.

If Tcl script signature checking is enabled, different actions can take place when a Tcl script is executed. If the signature of the Tcl script matches the digital certificate, the Tcl script will be executed immediately. If the signature fails to be verified, the following choices are available, depending on the IOS configuration:

  • The script can be immediately stopped.
  • The script can be allowed to run even though the signature check failed, in a special "safe" Tcl mode. The "safe" TCL mode has a reduced number of keywords available and is thought to be less dangerous than the full Tcl mode.
  • The script can be allowed to run normally. This can be used for testing purposes, but would rarely be used in an actual live network. In effect, this turns off the security check.

To digitally sign a script, an IOS image containing the crypto feature set must be used. This means the image name contains the k9 feature set. For example, the following image contains the crypto feature: c7200-adventerprisek9-mz.

The following example details how to correctly sign a Tcl script with a digital signature, using a UNIX host as the certificate authority (CA) server. As an alternative, a CA can also be created using other operating systems or can be hosted commercially.

A CA is a trusted third party that maintains, verifies, enrolls, distributes, and revokes public keys. It is for that very reason that the CA must be secure.

The previous examples assumed that Bob or Alice had the other's public key. But how does Bob know that the key he has is really from Alice? There are a couple of answers to that question:

  • Alice and Bob exchanged public keys out-of-band. This works fine in a small environment, but when there are hundreds or thousands of devices, manually exchanging keys becomes difficult.
  • A CA is used to maintain all certificates.

This is where a CA really shows its value. The CA maintains the public keys or certificates, usually in an X.509 format. Key exchange is as follows:

  • Step 1. Before Bob can verify Alice's public key, he must have the CA public key, which should be exchanged out-of-band.
  • Step 2. When Bob needs Alice's public key, he sends a request to the CA.
  • Step 3. The CA signs Alice's public key with the CA private key, consequently verifying the origination and sends it to Bob.
  • Step 4. Bob uses the CA public key to validate Alice's public key.

You must complete the following steps to sign a Tcl script:

  • Step 1. Decide on the final Tcl script contents (myscript).
  • Step 2. Generate a public/private key pair.
  • Step 3. Generate a certificate with the public key.
  • Step 4. Generate a detached S/MIME pkcs7 signature for the script you created (myscript) using the private key.
  • Step 5. Modify the format of the signature to match the Cisco style for a signed Tcl script and append it to the end of the script you created (myscript).

Step 1: Decide on the Final Tcl Script Contents (Myscript)

Finalize any last-minute changes needed to the script text file. After the Tcl script has been signed, no more changes may be made.

Step 2: Generate a Public/Private Key Pair

The private key must always be kept private! Failure to do so would allow anyone in possession of the private key to sign Tcl scripts as if they were written by the original author.

To generate a key pair, you can use the open source project OpenSSL. Executable versions of the OpenSSL are available for download at http://www.openssl.org

Using a UNIX host or similar, run the following command to generate a key pair (this example uses a 2048-byte key):

$ openssl genrsa -out privkey.pem 2048
Generating RSA private key, 2048 bit long modulus
..........................................+++
...............................................................................+
++
e is 65537 (0x10001)
$

As you can see from the directory, the following file has been created:

$ ls -l
total 5
-rw-r--r-- 1 joe mkgroup-l-d  114 May 28 10:23 myscript
-rw-r--r-- 1 joe mkgroup-l-d 1679 May 28 10:23 privkey.pem
$

The new file is called privkey.pem and contains both the private key and public key. The file needs to be kept in a secure location because it holds the private key.

Next, extract the public key from the key pair file:

$ openssl rsa -in privkey.pem -pubout -out pubkey.pem
writing RSA key
$

As you can see from the directory, the following file has been created:

$ ls -l
total 6
-rw-r--r-- 1 joe mkgroup-l-d  114 May 28 10:23 myscript
-rw-r--r-- 1 joe mkgroup-l-d 1679 May 28 10:23 privkey.pem
-rw-r--r-- 1 joe mkgroup-l-d  451 May 28 10:25 pubkey.pem
$

Now there are two separate files, one that contains the pair of keys (privkey.pem) and another file that contains only the public key (pubkey.pem).

Step 3: Generate a Certificate with the Key Pair

To create a certificate, we must answer a few questions. These answers will be stored along with the certificate, in case any concerns arise later about where the certificate comes from:

$ openssl req -new -x509 -key privkey.pem -out cert.pem -days 1095

You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a distinguished name (DN). There are quite a few fields, but some may be left blank.

For some fields there will be a default value. If you enter a period (.), the field will be left blank:

Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:California
Locality Name (eg, city) []:San Jose
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Acme Inc.
Organizational Unit Name (eg, section) []:Central Unit
Common Name (eg, YOUR name) []:Joe
Email Address []:joe@xyz.net

As you can see from the directory, the following cert.pem file has been added:

$ ls -l
total 10
-rw-r--r-- 1 joe mkgroup-l-d 1639 May 28 10:26 cert.pem
-rw-r--r-- 1 joe mkgroup-l-d  114 May 28 10:23 myscript
-rw-r--r-- 1 joe mkgroup-l-d 1679 May 28 10:23 privkey.pem
-rw-r--r-- 1 joe mkgroup-l-d  451 May 28 10:25 pubkey.pem
$

The certificate has now been generated in the file cert.pem. This certificate will later be transferred to the IOS router for the router to perform the signature check on the signed Tcl script.

Step 4: Generate a Detached S/MIME pkcs7 Signature for Myscript Using the Private Key

When the script is signed, a new file is generated called myscript.pk7, which contains the signature:

$ cat myscript
puts hello
puts "argc = $argc"
puts "argv = $argv"
puts "argv0 = $argv0"
puts "tcl_interactive = $tcl_interactive"
$
$ openssl smime -sign -in myscript -out myscript.pk7 -signer cert.pem -inkey pr
ivkey.pem -outform DER –binary
$

The myscript.pk7 file has been added:

$ ls -l myscript.pk7
-rw-r--r-- 1 joe mkgroup-l-d 1856 May 28 10:30 myscript.pk7
$

To validate that the signature matches the myscript certificate we generated earlier, perform the following:

$ openssl smime -verify -in myscript.pk7 -CAfile cert.pem -inform DER -content
myscript
puts hello
puts "argc = $argc"
puts "argv = $argv"
puts "argv0 = $argv0"
Verification successful
puts "tcl_interactive = $tcl_interactive"
$

The "Verification successful" message indicates that myscript matches the contents of the signature.

Step 5: Modify the Format of the Signature to Match the Cisco Style for Signed Tcl Scripts and Append It to the End of Myscript

Now that a signature for myscript has been generated, we still need to make some formatting changes to put myscript in the correct format for Cisco IOS to understand.

The format of a signed Tcl script is as follows:

Actual Tcl script contents in plain test
...
#Cisco Tcl Signature V1.0
#Actual hex data of the signature

The signature portion of myscript is inserted after the hash character (#). Tcl always treats this as a comment. If this script is executed on an IOS router that does not know about Tcl script signature checking, the router will simply ignore these commented lines.

The signature must be converted to a hex format instead of binary:

$ xxd -ps myscript.pk7 > myscript.hex
$

The directory listing shows that the file was created:

$ ls -l myscript.hex
-rw-r--r-- 1 joe mkgroup-l-d 3774 May 28 10:42 myscript.hex
$

Next, a helper script is used to place the #Cisco Tcl Signature V1.0 and the # characters in the new signature file.

You can show the contents of the file by using the cat command:

$ cat my_append
#!/usr/bin/expect
set my_first {#Cisco Tcl Signature V1.0}
set newline {}
set my_file [lindex $argv 0]
set my_new_file ${my_file}_sig
set my_new_handle [open $my_new_file w]
set my_handle [open $my_file r]
puts $my_new_handle $newline
puts $my_new_handle $my_first
foreach line [split [read $my_handle] "\n"]  {
   set new_line {#}
   append new_line $line
   puts $my_new_handle $new_line
}
close $my_new_handle
close $my_handle
$

Initiate the helper script using the following syntax:

$ ./my_append myscript.hex
$

The directory listing shows the myscript.hex and myscript.hex_sig files:

$ ls -l myscript.hex*
-rw-r--r-- 1 joe mkgroup-l-d 3774 May 28 10:42 myscript.hex
-rw-r--r-- 1 joe mkgroup-l-d 3865 May 28 10:56 myscript.hex_sig
$

Lastly, the signature file and the script file must be concatenated:

$ cat myscript myscript.hex_sig > myscript.tcl
$

The directory listing shows that the file was created:

$ ls -l myscript.tcl
-rw-r--r-- 1 joe mkgroup-l-d 3979 May 28 10:58 myscript.tcl
$

The signed Tcl script has finally been generated (myscript.tcl)!

The following script combines many of the preceding steps and will help to automate the process:

#!/bin/sh
# the next line restarts using tclsh exec tclsh "$0" "$@"

proc PrintUsageInfo {} {
         puts {usage:  signme input_file [-c cert_file] [ -k privkey_file]} }

set cert_file cert.pem
set privkey_file privkey.pem

if {$argc == 0} {
    PrintUsageInfo
    exit -1
}

set state flag
set cnt 0
foreach arg $argv {
    switch -- $state {
        flag {
            switch -glob -- $arg {
               \-c {
                   set state cert
               }
               \-k {
                   set state key
               }
               default {
                   if {$cnt == 0} {
                       set filename $arg
                   } else {
                       PrintUsageInfo
                       exit -1
                   }
               }
           }
       }
       cert {
           set cert_file $arg
           set state flag
       }
       key {
           set privkey_file $arg
           set state flag
       }
   }
   incr cnt
}

if {![string equal $state flag]} {
    PrintUsageInfo
    exit -1
}

if {[catch {set commented_signed_hex [exec openssl smime -sign -in $filename     -signer $cert_file -inkey $privkey_file -outform DER -binary | xxd -ps     | sed s/^/#/ ]} err]} {
    puts stderr "Error signing $filename - $err"
    exit -1
}

set signature_tag "\n#Cisco Tcl Signature V1.0"

if {[catch {set fd [open $filename a+]} err]} {
    puts stderr "Cannot open $filename  - $err"
    exit -1
}

puts $fd $signature_tag
puts $fd $commented_signed_hex
close $fd

puts "$filename signed successfully."
exit

To take advantage of the newly signed script, the IOS device must be configured with a certificate.

After logging in to the IOS device and establishing access to configuration mode, complete the following steps:

  • Step 1. Configure and enroll in a trust point using the cert.pem file. At the prompt, paste the certificate into the terminal. That is, paste the contents of the cert.pem file beginning after "-----BEGIN CERTIFICATE-----" and ending before "-----END CERTIFICATE-----".":
    PE11(config)#crypto pki trustpoint TCLSecurity
    PE11(ca-trustpoint)#enrollment terminal
    PE11(ca-trustpoint)#crypto pki authenticate TCLSecurity
    Enter the base 64 encoded CA certificate.
    End with a blank line or the word "quit" on a line by itself
    -----BEGIN CERTIFICATE-----
    MIIEjDCCA3SgAwIBAgIJANOb35p5QONbMA0GCSqGSIb3DQEBBQUAMIGKMQswCQYD
    VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTERMA8GA1UEBxMIU2FuIEpvc2Ux
    EjAQBgNVBA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41swDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEA
    F+W1JWf56IJPjYT0f2MForE3/gsKMgUvMh+kyf4Fcgvdh4WuKUEwTVBHpHglOYyL
    XfNZe6ILf9e3SgmXsqJOwAu/qK8d5uMwZ4d8TVoZqN1QmJPhvBcp7WZS8EvMVAWU
    vwo8SUgDUY1QzXPa5R333T0k1Vo+wxc7c4zftH/gbbqrGGgP5EAlXKvX75Z/dafv
    d/jPl4DniOlwz54ieRwjRU7B9w80Oa8EQeGRnsuNBcXRYqNoHJMRQK2xelqBL//8
    10TEQeAoN3WjHBkqLXjf6HasnhfnwoNpNEn+ni5xN5uigbmuBzS1TCeevve/Y0ix
    NnU3fSYpIOnb1tZLBbYY7A==
    -----END CERTIFICATE-----
    Certificate has the following attributes:
            Fingerprint MD5: 856A9FF2 23AF24B0 8422B4FC 1E9E4153
           Fingerprint SHA1: 35248814 47468190 4A1A3B6C 9D60C2A8 0B99BB0C
    % Do you accept this certificate? [yes/no]: yes
    Trustpoint CA certificate accepted.
    % Certificate successfully imported
    Verify that the trust point was accepted correctly:
    PE11#show crypto pki trustpoints
    Trustpoint TCLSecurity:
        Subject Name:
        e=joe@xyz.net
        cn=Joe
        ou=Central Unit
        o=Acme Inc.
        l=San Jose
        st=California
        c=US
               Serial Number: 0x0D39BDF9A7940E35B
        Certificate configured.
    It looks correct because we see the expected information that was entered when we generated the certificate.
  • Step 2. Configure the IOS device to require that all Tcl scripts be verified against the certificate before running. In this example, if a script does not pass the security check, it will not be allowed to execute:
    PE11(config)#scripting tcl trustpoint name TCLSecurity
    PE11(config)#scripting tcl securemode
    PE11(config)#scripting tcl trustpoint untrusted terminate
          
    All Tcl scripts that are run on the router must now perform a signature check. Alternatives for executing scripts include the following:
    • Execute: Run the script even if the Tcl script fails verification
    • Safe-execute: Execute the script in safe mode when the Tcl script fails verification.
  • Step 3. After copying the script myscript.tcl to disk0: of the IOS device, you can initiate it using the following command:
    PE11#tclsh disk0:myscript.tcl
    hello
    argc = 0
    argv =
    argv0 = unix:myscript.tcl
    tcl_interactive = 0
3. Tcl Script-Failure Scenario | Next Section Previous Section

Cisco Press Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Cisco Press and its family of brands. I can unsubscribe at any time.

Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Cisco Press products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@ciscopress.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children

This site is not directed to children under the age of 13.

Marketing

Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by Cisco Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.ciscopress.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020