Enfuse is an open-source command line utility that can accomplish focus stacking, although it more typically is used for exposure fusing. The underlying algorithm selects pixels out of a stack of images based upon specific selection criteria. The main three criteria are exposure, contrast, and saturation. If you weight exposure as the main selection criteria, you get exposure fusing. If you select contrast as the main selection criteria, you get focus stacking. You will also want to select hard masking.
However, enfuse only does the fusing of the stack. It does not do alignment of the stack. For that, you will need a separate tool, such as align_image_stack, which is included in the panotools open source project.
In addition, there are many GUI front-ends that can invoke both command line tools together for you to perform either focus stacking or exposure fusion. Two of the most popular would be the panorama stitching package, Hugin, and the Lightroom plugin, Lr/Enfuse. You could also use Hugin simply to align the images and then run enfuse via the EnfuseGUI frontend.
See also: http://blog.patdavid.net/2013/01/focus-stacking-macro-photos-enfuse.html