Home

Spring Framework Security Vulnerability Part 2

What you can learn from CVE-2010-1622

I've already talked about CVE-2010-1622 and what SpringSource could have done better when dealing with this security issue.
Today I want to focus on what you as a developer or system administrator can learn from the bug.

What can developers learn from CVE-2010-1622?

The exploit requires manipulating the class loader property so that it will download code from an external site. So you can prevent the attack by disallowing modifications of the class loader and by disallowing your application to download and run code from external sites.

Be explicit! Explicitly allow binding of certain properties. This prevents the exploit from working as there is no valid use case that requires access to the class property. Explicitly whitelisting properties also makes sure users cannot change the id of the object bound to a form or altering data that is managed internally like "date of creation" or "last modified by" properties.

To prevent code from external sites being downloaded and executed you can make sure your applications behaves well when run with a security manager. While this is a common concept used for client side code like applets it is far less common for server side applications. Tomcat usually works well with a security manager though it is not enabled by default. Making sure you appplications works with a security manager is also a variant of being explicit: You explicitly grant certain privileges to your code bases and disallow everything else that might be abused by attackers.

What can system administrators learn from CVE-2010-1622?

Your applications should run in a demilitarized zone where they are unable to access the internet or your intranet. If you really need access to external resources use a proxy server and white list the URLs your application needs to contact. Doing so prevents attackers from making your application download external code.

If your applications are built in a way that they work with a security manager use it! For Tomcat there is a short Howto available.

Spring Framework Security Vulnerability Part 1

What SpringSource can learn from CVE-2010-1622

Spring Source recently published CVE-2010-1622. The advisory describes a vulnerability that affects Spring Framework prior to 3.0.3 and allows attackers to execute arbitrary code.

What could SpringSource have done better?

When Spring Source announced the release of 3.0.3 they reported to have fixed "more than a hundred minor issues" — no indication of the security fix. This could be understandable as they have released the fix 2 days prior to publishing the advisory. I do not understand why they did not announce it later however. The advisory was published as silently as possible although the vulnerability is rated critical, can be exploited remotely and probably affects a large number of applications.
I would have preferred receiving the security advisory through the usual channels used for announcements in addition to the security team page.

Having a look at cve.mitre.org reveals another interesting fact. The CVE id was assigned on April, 29th. That is almost 2 months before the advisory was published. The bug was fixed on May, 27th.
Why does it take more than 4 weeks for a 3 line fix? Why does it take almost 3 additional weeks after the fix to announce the vulnerability?
I would have preferred a priority fix as soon as possible after discovery and a release following short time after that.

Finally SpringSource dicided not to provide a fixed release for dm Server, a product based on Spring Framework, which is also vulnerable. Users are advised to manually patch it instead. SpringSource also continues to provide the vulnerable dm Server 2.0.2 for download without any warning.
I would have preferred to receive a fixed release of dm Server instead of seeing SpringSource continue to ship products containing known security issues.

What can you learn from CVE-2010-1622?

I will follow up with the lessons learned for application developers and system administrators in the next days. Stay tuned.

There is also an interesting analysis of the issue at blog.o0o.nu.

Code Style: Braces, Indentation and Line Length

What we do and why.

We've recently revisted our Java Coding Conventions. For several years we are now using a style based on the excellent book The Elements of Java Style by RougeWave. It follows the Sun Code Style in many aspects and adds a lot of reasoning.

Our Code Style differs mainly in two aspects:

  • We place curly braces on new lines
  • We use a maximum line length of 130 characters

I am well aware that there are religious opinions regarding those questions but after reconsidering our style we came to the conclusion that both differences actually make sense.

Lining up curly braces vertically (called Allman or ANSI style) makes it easy to check that the braces match. The indented code is clearly set apart from the containing statement by lines that are almost completely whitespace which makes the code easier to read. In contrast to K&R style it consumes more space but today's screens are well capable to show more than the ancient 24 lines.

Good:

if (condition)
{
    body;
}

Bad:

if (condition) {
    body;
}

The reason to limit the line length to 80 characters comes from the limitation of old printers that usually printed 80 characters per line. We seldomly print code on paper and modern printers are well capable to print at other resolutions. Limiting us to to 80 characters would waste a lot of screen space as with a decent screen size showing 130 characters still leaves enough place for the IDE to show up additional frames including outlines and project files left and right to the code.

What we learned: Use the mainstream conventions by default. Challenge them and check if the underlying assumptions hold true in your environment. Only derive if there is enough benefit to justify the change.

Java Applications on Privileged Ports

Using Java Service Wrapper and authbind on Ubuntu

I am running most of my Java applications with Java Service Wrapper on Ubuntu. Most of these applications can run on unprivileged ports above 1024, e.g. Tomcats running behind an Apache http reverse proxy or the Openfire XMPP server that uses ports above 1024 by default. However there are exceptions like the LDAP server ApacheDS or Tomcats that do not require the features of httpd in front of them.

If you want to run Java applications on privileged ports below 1024 there are several options you can choose from:

To use authbind follow these steps:

Step 1: Install and configure authbind

Install authbind from the Ubuntu repository:

# aptitude install authbind

For each port your application should be able to bind to create a file in /etc/authbind/byport and make in executable by the user that runs your application. For ApacheDS I did the following:

# cd /etc/authbind/byport
# touch 389 636
# chown apacheds:apacheds 389 636
# chmod 700 389 636

This results in the following files:

# ls -l /etc/authbind/byport/
total 0
-rwx------ 1 apacheds apacheds 0 2010-05-04 21:24 389
-rwx------ 1 apacheds apacheds 0 2010-05-04 21:24 636

More information on access control is available in authbind (1).

Step 2: Update wrapper.conf

Authbind works by overloading the bind function in libc. This is done by setting the environment variable LD_PRELOAD. If you are using Java Service Wrapper the easiest way to do this is to add the following line to your wrapper.conf:

set.LD_PRELOAD=/usr/lib/authbind/libauthbind.so.1

As authbind only supports IPv4 you must prevent your application from binding to the IPv6 port as well. This can be achieved by setting the system property java.net.preferIPv4Stack in wrapper.conf:

wrapper.java.additional.1=-Djava.net.preferIPv4Stack=true

That's it!

This approach works with any Java application and is not limited to ApacheDS. Have a look at A Better Tomcat for Ubuntu and Debian by MuleSource to see how they are using authbind without Java Service Wrapper to make Tomcat run on standard HTTP ports.

Book Review: Modular Java

Creating Flexible Applications with OSGi and Spring by Craig Walls

Modular Java by Craig Walls is a book on building modular Java applications on OSGi platforms.

Published in the Pragmatic Bookshelf series it keeps up to the standards of that great series by presenting content that matters in a format that makes you try it out immediately.

OSGi's value proposition is to keep complexity in software products manageable. It keeps modules isolated from each other and encourages loose coupling through publishing and consuming services. You can think of OSGi as an incarnation of service oriented archietcure (SOA) within the Java Virtual Machine. OSGi has its roots in the embedded systems environment and became popular for desktop applications with Eclipse using it as their core infrastructure. From embedded to desktop OSGi is currently coming to the server side.

Craig's book introduces the basics of OSGi, shows how it isolates modules by its unique approach to classpath handling and gives you an overview of the concept of OSGi services. One easy to follow example application is used consistently throughout the book to show the various aspects.
Most of the time the book uses Equinox as runtime but Felix and Knopflerfish are also mentioned. For building bundles Modular Java makes use of Pax especially Pax Construct. It does not mention Bundlor, Bnd or Tycho in depth. Especially the Maven based Tycho stack sounds really promising so it's unfortunate that it isn't covered. I guess however this is just an attribution to the current speed of development in the OSGi tooling space.

Spring Dynamic Modules are an attempt to bring the principles of Spring Framework to OSGi. In the spirit of Spring Framework Dynamic Modules (DM) build on proven solutions (OSGi in this case) and make them easier to use. They eliminate a lot of boilerplate code that is normally require to handle OSGi services that may appear and disappear at any time. Spring-DM also provides integration with Spring Application Contexts and has support for web applications through an extender. Spring-DM is covered really well by the book. An appendix describes the new OSGi Blueprint Services that are an attempt to standardize the ideas of Spring-DM. Spring's new dm Server is not covered.

The book focuses on the core concepts and shows the benefits of using OSGi for application development. The target audience are experienced Java developers. It is very well written, easy and fun to read and serves as a great introduction. I recommend the book to Java developers who consider making use of OSGi in future projects.

Tags :

Asterisk-Java 1.0.0.M3 Released

Milestone 3 with support for OSGi and SLF4J

We have released milestone 3 of Asterisk-Java 1.0.0. Next to a few bug fixes this new milestone makes Asterisk-Java OSGi compliant, adds support for the modern SLF4J logging framework and makes debugging easier through built-in support for network tracing.

You can browse the full changelog to see which issues have been resolved.

The new release is available as a plain jar and a zip distribution at http://asterisk-java.org/download/1.0.0.M3. You can also browse the documentation and javadocs online.

The new milestone is also available through Maven:

<dependency>
  <groupId>org.asteriskjava</groupId>
  <artifactId>asterisk-java</artifactId>
  <version>1.0.0.M3</version>
</dependency>

Please report back any issues you encounter while using milestone 3 through our issue tracker. If you like to have a certain feature or bug fix included in the next version vote for it in Jira.

References

Built-in Support For Network Tracing

Using the org.asteriskjava.trace system property

Up to now the preferred way to obtain traces of the communication between Asterisk-Java and Asterisk was using tcpdump, wireshark or ngrep as described in Debugging Manager API. Having a full log of the direct network communication is often the only way to resolve issues related to problems in the Manager API or Fast AGI.

To make it easier for our users to obtain these traces we have now included a tracing feature directly into Asterisk-Java. You can enable it at runtime by setting the system property org.asteriskjava.trace to true. On the command line:

java -Dorg.asteriskjava.trace=true ...

Trace files are written to the temp dir by default ("java.io.temp"). You can specify an alternate location by using the org.asteriskjava.trace.directory system property:

java -Dorg.asteriskjava.trace=true \
     -Dorg.asteriskjava.trace.directory=/opt/traces ...

Log files contain a timestamp and the IP addresses and ports of the involved servers in their file name. A typical file looks like this:

2009-10-20T21:51:18.414CEST <<< Asterisk Call Manager/1.1
2009-10-20T21:51:18.536CEST >>> action: Challenge
                            >>> actionid: 888911819_0#
                            >>> authtype: MD5
                            >>>
2009-10-20T21:51:18.601CEST <<< Response: Success
2009-10-20T21:51:18.663CEST <<< ActionID: 888911819_0#
2009-10-20T21:51:18.664CEST <<< Challenge: 336054137
2009-10-20T21:51:18.665CEST <<<
2009-10-20T21:51:18.705CEST >>> action: Login
                            >>> actionid: 888911819_1#
                            >>> authtype: MD5
                            >>> username: manager
                            >>> key: ed0481d08ae7832fb
                            >>>
2009-10-20T21:51:18.768CEST <<< Response: Success
2009-10-20T21:51:18.831CEST <<< ActionID: 888911819_1#
2009-10-20T21:51:18.832CEST <<< Message: Authentication accepted
2009-10-20T21:51:18.833CEST <<<

This new feature is already part of the latest Asterisk-Java 1.0.0-CI-SNAPSHOT and will be shipped with milestone 3.

Please consider attaching a trace file to your bug reports in the future. It speeds up bug fixing considerably.

Asterisk-Java goes OSGi

Asterisk-Java now distributed with proper OSGi manifest headers

We are currently working on making Asterisk-Java OSGi compliant to make it easier for those users who want to use Asterisk-Java in an OSGi container like Equinox. This means Asterisk-Java will contain the proper bundle headers in its MANIFEST.MF and will follow the OSGi rules for version names. The new version names for Asterisk-Java are similar to those used by Spring Framework:

1.0.0.CI-SNAPSHOT
Continious integration snapshot releases
1.0.0.M3
Milestone releases
1.0.0.RC1
Release candidates
1.0.0.RELEASE
Final release
1.0.0.SR01
Service release with emergency bug fixes

The first OSGi compliant snapshots of Asterisk-Java are now available for download: Asterisk-Java 1.0.0.CI-SNAPSHOT. The old 1.0.0-SNAPSHOT releases will no longer be updated.
For those developers that are not interested in OSGi nothing will change. The OSGi manifest headers added to Asterisk-Java are simply ignored when run in a non-OSGi environment.

The new MANIFEST.MF looks like this:

Manifest-Version: 1.0
Bundle-Description: The free Java library for Asterisk PBX integration.
Bundle-DocURL: http://asterisk-java.org/
Bundle-ManifestVersion: 2
Bundle-Name: Asterisk-Java
Bundle-SymbolicName: org.asteriskjava
Bundle-Vendor: reucon
Bundle-Version: 1.0.0.CI-SNAPSHOT
Export-Package: org.asteriskjava;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.config;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.config.dialplan;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.fastagi;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.fastagi.command;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.fastagi.reply;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.manager;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.manager.action;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.manager.event;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.manager.response;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.manager.util;version="1.0.0.CI-SNAPSHOT",
 org.asteriskjava.live;version="1.0.0.CI-SNAPSHOT"

If you are looking for a ready to use OSGi based framework to develop AGI scripts for Asterisk on SpringSource dm Server you may also want to check ajdmserver.

Code Style: Final Arguments

Don't mark arguments as final as it clutters your code

Java allows you to make arguments final by declaring them as final in the argument list of the method declaration:

public void doSomething(final String foo)
{
  ...
}

This means that inside the method you cannot change what the argument reference points to, i.e. it prevents you from doing things like this:

  foo = "bar";

It is bad style to change the reference an argument points to. You should treat all arguments as if they were marked final. It would have even been a good idea to make this a language feature and have Java treat all arguments as final by default.

However does this justify to declare all arguments as final? Some people suggest this though I haven't seen this in the wild very often.

The pros:

  • enforces not changing the reference an argument points to

    The cons:

    • makes method signatures longer and harder to read
    • takes longer to write, being lazy is a virtue

    There is one thing to note: Changing the reference the argument points to does not actually change the value of the caller's variable passed to the method:

    public void testDoSomething()
    {
      String foo = "foo";
      doSomething(foo);
      System.out.println(foo); // still prints "foo"
    }
    
    public void doSomething(String foo)
    {
      foo = "bar";
    }
    

    However if you pass an object that is not immutable and you change the state inside the called method you actually do change the caller's data. This is nothing a final modifier can prevent you from doing though it may be a source of trouble if not properly stated in the contract of the method.

    So to sum it up: You should not change the reference an argument points to as it causes confusion. You can prevent this by adding the final modifer. Doing so however clutters your code and thus shouldn't be done (except when needed to use the argument in an inner class). Pay attention to not change the state of an object passed to a method if that's not part of the method's contract.

    The same applies to some extend to final local variables. Use them where they make your code easier to understand but not everywhere you could. If you are a fan of final have a look at Scala's val keyword.

    Tags :

Users: ADempiere Asterisk Integration

Calling Contacts from ADempire

ADempiere is a collection of Open Source ERP applications.

By leveraging Asterisk-Java the Asterisk integration for ADempiere provides support for calling contacts directly from within ADempiere.

Tags :

Asterisk-Java Sync to Maven Central Repo

Asterisk-Java now autmatically sync'ed to central

The released Asterisk-Java artifacts are now automatically published to Maven's central repository. This includes our milestone releases 1.0.0-m1 and 1.0.0-m2.

If you are already using Maven for development that means to you that you no longer have to download Asterisk-Java in order to use it. You can just declare a dependency and Maven automatically downloads it from central.

The Maven coordinates for Asterisk-Java are:

<dependency>
  <groupId>org.asteriskjava</groupId>
  <artifactId>asterisk-java</artifactId>
  <version>1.0.0-m2</version>
</dependency>

SSO for RoundCube Webmail with Atlassian Crowd

Easy single sign-on

Atlassian Crowd is a single sign-on and identity management tool by Atlassian that integrates well with their suite of software engineering and collaboration tools like JIRA, Confluence and Crucible. It offers a SOAP API that allows integration into arbitrary third-party systems. Integrating a webmail system with Crowd is quite easy. I've choosen RoundCube Webmail 0.2.2 as an example. RoundCube is based on PHP and has a nice and clean user interface and a well-written code base.

Step 1: Basic Integration

There is a PHP integration library that can be used as a starting point. It provides the methods for SSO but lacks the convenience of Crowd's HttpAuthenticator. Implementing a simple PHP version of the HttpAuthenticator was the first step. My implementation uses APC to store the application token and validates every request with Crowd.

Step 2: Dovecot Masteruser

While the original version of RoundCube uses the user's username and password to connect to the IMAP store that's no longer possible with the crowdified version as it doesn't have access to the user's password. One solution is to use dovecot's masteruser feature. With that configuration in place RoundCube can access the user's mailbox by using its own password instead of the user's password.

Step 3: Configuration

That's it. Quite simple. If you like you can have a look at my patch. Check config/main.inc.php and provide the username and password of your dovecot masteruser as well as the application name, credential and service URL for Crowd.

Nexus vs. Artifactory

Choosing a Maven Repository Manager

Until now we didn't use a repository manager for Maven. Our repos were a plain directory structure on the file system served by Apache. Uploading was done using Apache's WebDAV capabilities with a simple authentication against our LDAP directory:

<Location /maven>
  Options Indexes

  DAV On
  AuthType Basic 
  AuthName "reucon Maven Repositories"
  AuthBasicProvider ldap
  AuthLDAPURL ldap://ldap.myorg.com/o=myorg?uid?sub?(objectClass=person)
  AuthLDAPBindDN uid=httpd,ou=techusers,o=myorg
  AuthLDAPBindPassword secret
  AuthzLDAPAuthoritative off

  Require valid-user
  FileETag None
</Location>

We are maintaining four repositories: one for our public Open Source artifacts and one for proprietary internal artifacts along with corresponding snapshot repositories. Access to the internal repository was limited based on an IP address range.

There are multiple reasons for us to use a repository manager:

  • Unified access to repositories
    In the old days all you needed was the central repo (formerly known as ibiblio). Times have changed and now many of our projects require artifacts from a variety of different repositories. It seems many organisations prefer having their own repos instead of publishing to central. This includes SpringSource, JBoss, Codehaus and several snapshot repos like for Apache. Maintaing a list of these repos in each developers settings.xml is a pity and including them in the poms makes things even worse in the long run.
  • Finer grained access control
    On the one hand we need access to our internal repo from outside of our internal network, so IP based access control no longer works well. On the other hand not all developers should be allowed to publish releases. Some kind of role based access control was needed.
  • Automated creation of the Nexus index
    A Nexus index is basically a zip file containing a lucene index of the artifacts in a repository. Most Maven IDE plugins now support searching for artifacts when adding dependencies to a project. To make this work the IDE must be be able to download an up to date index of the repositories.
  • Web based artifact search
    You may know mvnrepository.com a web site to search for artifacts in the central repo. I've often used it to find the correct version and maven coordinates for a dependency. A similar solution for our internal repositories would be nice.

There are a lot more reasons to use a repository manager like faster builds through caching of artifacts, black- or whitelisting of artifacts based on corporate standards but those listed above were the key factors for us.

There are three products that can be used: Apache Archiva, Sonatype Nexus and JFrog's Artifactory. There is a feature matrix that shows their features.

I dropped Archiva because its development is rather slow and it is missing some important features like grouped repositories. So Nexus and Artifactory remained. I came across two blog postings from January: Sonatype's comparison and JFrog's response. Combined they provide a lot of insight. Here is my own comparison:

Security

Good LDAP integration is a must have. Artifactory supports this out of the box, Nexus does not include LDAP support in its Open Source edition. It is a Nexus Pro feature. I do understand that Sonatype is trying to sell its Pro version but LDAP support is really a basic and vital feature. Fortunately it is not too difficult to implement a custom authenticator for Nexus and in fact there is already a project at Google Code called nexus-ldap that adds free LDAP support to Nexus. Both Artifactory and Nexus support fine grained role based authorization. One problem I faced with Artifactory was that requiring authentication seems to be a global setting, so you either require authentication for all repositories or for none. This is less flexible than Nexus which allows us to make our Open Source repository available without authentication and requires authentication only for deployment and for our internal repositories.
Artifactory has a nice additional feature that eliminates the need to store the user's password in Maven's settingx.xml in clear text by encrypting the password with a user specific key stored in Artifactory. This is an interesting approach and I would like to see this concept being used more widely (e.g. for Subversion).

Storage

How the repository manager stores artifacts and meta data is the biggest difference between Artifactory and Nexus. Artifactory uses a Java Content Repository (JCR) that can optionally be hosted in a MySQL database.
Nexus stores artifacts and meta data in the file system. It uses the maven layout so it is easy to access the repositories managed by Nexus externally. This becomes handy not only for migration but also when synchronizing to central through rsync. Though Artifactory offers an export feature having my repository data available directly on the file system makes me feel better.

Searching and Indexing

Both Nexus and Artifactory publish indexes (based on Lucene) and provide a web interface for searching artifacts stored in the repository. Nexus takes this one step futher and also allows searching for artifacts in proxied repositoreis not yet stores in the local repository. This is really handy and eliminates the need to use external sites to search for artifacts and they current version.

Conclusion

Before I found nexus-ldap I was about to choose Artifactory over Nexus. After that I prefer Nexus for the file system based storage and better searching.

References

Asterisk-Java 1.0.0-m2 Released

On the way to the final 1.0.0 release

As most of the users already make use of many new features in 1.0.0-SNAPSHOT it is time to push the final release out of the door. As a first step I've released milestone 2 of 1.0.0 called 1.0.0-m2. Have a look at the changelog to see which bugs have been fixed and which new features are included.

Most notably milestone 2 includes support for the 1.6 series of Asterisk as well as support for using scripting languages with the FastAGI server.

The new release is available as a plain jar and a zip distribution at http://asterisk-java.org/download/1.0.0-m2. You can also browse the documentation and javadocs online.

Please report back any issues you encounter while using milestone 2 through our issue tracker. If you like to have a certain feature or bug fix included vote for it.

References

Maven Release with Subversion 1.5 and 1.6

A fix for File '...' already exists

There is a problem with the maven-release-plugin when used with recent versions of Subversion. It stared at version 1.5.1 of Subversion and made the release:prepare command fail because Maven was no longer able to tag the release.

You may have encountered the following error with release:prepare:

svn: File '...' already exists

One reason for this can be SCM-406.

For some time I've worked around this issue by doing my releases on a machine with an older version of Subversion.

A better solution is to use the latest version of the maven-release-plugin (2.0-beta-9 at the moment) and set the remoteTagging property to true:

<build>
  <plugins>
    <plugin>      
      <artifactId>maven-release-plugin</artifactId>
      <version>2.0-beta-9</version>
      <configuration>     
        <remoteTagging>true</remoteTagging>
        <preparationGoals>clean install</preparationGoals>
        <autoVersionSubmodules>true</autoVersionSubmodules>
        <tagBase>...</tagBase>
      </configuration>
    </plugin>     
  </plugins>
</build>

Keep in mind that you should always specify the exact version of the plugins you are using. This not only makes sure you get what you need it also ensures that the build is reproducible in the future and works consistently accross different machines.

Tags :

Security Issues Caused By External Hosting

Deutsche Lufthansa leaks personal data

Thomas has a nice example of how Deutsche Lufthansa has leaked personal data through an entertainment site operated by an external agency.

Most companies have strict rules for handling personal data and installed security policies for secure handling of sensitive information. Therefore enterprise data centers are usually quite secure. However the corporate processes that are required to keep the standards high are slow and expensive. This causes some companies to skip them in favor of faster and cheaper alternatives.

One solution is to accept hosting offers by the agencies that build the sites. The problem is that they are seldomly capable of providing a secure environment. It's just not their business. The result is that sites with sensitive data are operated in shared hosting environments by unskilled persons out of control of corporate IT. It's only a matter of time until security issues pop up and companies can be glad if they are informed before any data is stolen.

It just doesn't make sense to harden the front door if you open up a few back doors at the same time. The best security policies are worthless if companies are willing to bypass them for faster and cheaper alternatives. Maybe Thomas' story will help showing the value of corporate IT to those seeking alternatives without looking at the consequences.

Tags :

Scripting Support for FastAGI

Writing AGI scripts in Groovy, JavaScript, JRuby or PHP

Asterisk-Java 1.0.0 includes support for implementing AGI scripts in the scripting language of your choice. You still have the benefit of running on the JVM but for the implementation of your script you can now choose your favorite language.

I've prepared a small demo script that counts down from ten to zero. Then it plays a beep and waits for DTMF input to read the digit you've pressed back to you. You can exit by pressing star (*) or pound (#). To show you how this script looks like in the different languages it is implemented three times: In Groovy, JavaScript and PHP.

To get started just download the binary distribution of Asterisk-Java. Unpack it and run the asterisk-java.jar file from the unpacked directory.

$ cd asterisk-java-1.0.0-SNAPSHOT
$ java -jar asterisk-java.jar
May 13, 2009 1:26:16 AM org.asteriskjava.fastagi.DefaultAgiServer startup
INFO: Listening on *:4573.

The AGI scripts are put into the agi directory. There you'll also find the demo.groovy, demo.js and demo.php files. The lib directory contains additional libraries required to execute the scripts.

In addition to the functions provided by the scripting language Asterisk-Java adds two variables:

request
the request data including the dialed extension, the caller id, channel name, parameters and more
channel
for interacting with Asterisk, e.g. to stream files, receive DTMF digits or execute dialplan applications

Modify your dialplan and add extensions for the demo scripts:

exten => 2000,1,Agi(agi://localhost/demo.groovy)
exten => 2001,1,Agi(agi://localhost/demo.js)
exten => 2002,1,Agi(agi://localhost/demo.php)

If you are not running Asterisk-Java on the same server as Asterisk replace localhost by the hostname of the machine running Asterisk-Java.

Note that you will need at least Java 6 to make use of the new scripting support.

Asterisk-Java Lightning Talk @ JUGC

May, 29th 2009

I will give a short presentation of Asterisk-Java (in German) at the Java User Group Cologne (JUGC) on May 29th.

It will be a short overview of what Asterisk-Java can do and how it can be used to add phone support to Java applications. The presentation will have a duration of 5 to 10 minutes and include a small interactive demo that serves as a show case.

The main talk will be about JSF 2.0 vs Struts 2.1. I would be happy to meet a few Asterisk-Java developers over there.

The slides are available (in German) at slideshare.

Users: Asterisk and CTI, what’s that all about?

Some inspriation for playing with the Asterisk APIs

Sameh Shaker has posted some examples of what you can do with Asterisk using the Manager API and Fast AGI. I think it's a good starting point for new users of Asterisk-Java to get some inspiration for their own applications.

References

Tags :

Speech Recognition with Asterisk-Java

Using the Lumenvox engine with Java

The latest snapshot of Asterisk-Java contains support for the Asterisk Speech API. This makes writing AGI script that recognize speech as easy as writing AGI scripts for DTMF input.

All you need to get started is a recent version of Asterisk 1.6 and the Lumenvox Speech Engine. For development you can buy a starter kit from Digium for 50 USD.

In your AGI script you initialize the speech engine, load and activate a grammer and are ready to recognize speech. The speechRecognize() method takes a voice prompt as its first parameter. The prompt is played to the user and the users response is recognized. The user doesn't have to wait for the prompt to finish, he can start talking right away ("barge in"). The corresponding Java code looks like this:

speechCreate();
speechLoadGrammar("digits", grammarPath);
speechActivateGrammar("digits");
SpeechRecognitionResult result = 
  speechRecognize("speech-demo/prompt", 10);
speechDeactivateGrammar("digits");

The SpeechRecognitionResult provided by Asterisk-Java contains the result and the confidence score – a value between 0 and 1000 that indicates how sure the speech engine is that the result is correct. The Java code to evaluate the result looks like this:

if (result.isSpeech())
{
    if (result.getScore() > 990)
    {
        streamFile("speech-demo/absolutely-sure");
    }
    else if (result.getScore() > 800)
    {
        streamFile("speech-demo/pretty-sure");
    }
    else
    {
        streamFile("speech-demo/not-sure");
    }

    // say what we have recognized
    sayDigits(result.getText());
}       

Finally call speechDestory to end the speech recognition session (for a real application you probably want to do this in a finally block):

speechDestroy();

Pretty easy, isn't it?

You can have a look at the SpeechDemo AGI script or download the full demo that includes the latest snapshot of Asterisk-Java, the voice prompts and the AGI script.