001/*
002 * (C) Copyright 2013-2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Wojciech Sulejman
018 *     Florent Guillaume
019 *     Vladimir Pasquier <vpasquier@nuxeo.com>
020 */
021package org.nuxeo.ecm.platform.signature.core.sign;
022
023import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.SIGNED_CURRENT;
024import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.SIGNED_OTHER;
025import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.UNSIGNABLE;
026import static org.nuxeo.ecm.platform.signature.api.sign.SignatureService.StatusWithBlob.UNSIGNED;
027
028import java.io.File;
029import java.io.FileOutputStream;
030import java.io.IOException;
031import java.io.Serializable;
032import java.security.KeyPair;
033import java.security.KeyStore;
034import java.security.cert.Certificate;
035import java.security.cert.X509Certificate;
036import java.util.ArrayList;
037import java.util.Collections;
038import java.util.HashMap;
039import java.util.List;
040import java.util.Map;
041
042import org.apache.commons.io.FilenameUtils;
043import org.apache.commons.lang.StringUtils;
044import org.apache.commons.logging.Log;
045import org.apache.commons.logging.LogFactory;
046import org.nuxeo.ecm.core.api.Blob;
047import org.nuxeo.ecm.core.api.Blobs;
048import org.nuxeo.ecm.core.api.DocumentModel;
049import org.nuxeo.ecm.core.api.ListDiff;
050import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
051import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;
052import org.nuxeo.ecm.core.api.blobholder.SimpleBlobHolder;
053import org.nuxeo.ecm.core.convert.api.ConversionException;
054import org.nuxeo.ecm.core.convert.api.ConversionService;
055import org.nuxeo.ecm.platform.signature.api.exception.AlreadySignedException;
056import org.nuxeo.ecm.platform.signature.api.exception.CertException;
057import org.nuxeo.ecm.platform.signature.api.exception.SignException;
058import org.nuxeo.ecm.platform.signature.api.pki.CertService;
059import org.nuxeo.ecm.platform.signature.api.sign.SignatureAppearanceFactory;
060import org.nuxeo.ecm.platform.signature.api.sign.SignatureLayout;
061import org.nuxeo.ecm.platform.signature.api.sign.SignatureService;
062import org.nuxeo.ecm.platform.signature.api.user.AliasType;
063import org.nuxeo.ecm.platform.signature.api.user.AliasWrapper;
064import org.nuxeo.ecm.platform.signature.api.user.CUserService;
065import org.nuxeo.runtime.api.Framework;
066import org.nuxeo.runtime.model.ComponentInstance;
067import org.nuxeo.runtime.model.DefaultComponent;
068
069import com.lowagie.text.DocumentException;
070import com.lowagie.text.Rectangle;
071import com.lowagie.text.pdf.AcroFields;
072import com.lowagie.text.pdf.PdfPKCS7;
073import com.lowagie.text.pdf.PdfReader;
074import com.lowagie.text.pdf.PdfSignatureAppearance;
075import com.lowagie.text.pdf.PdfStamper;
076
077/**
078 * Base implementation for the signature service (also a Nuxeo component).
079 * <p>
080 * The main document is signed. If it's not already a PDF, then a PDF conversion is done.
081 * <p>
082 * Once signed, it can replace the main document or be stored as the first attachment. If replacing the main document,
083 * an archive of the original can be kept.
084 * <p>
085 * <ul>
086 * <li>
087 */
088public class SignatureServiceImpl extends DefaultComponent implements SignatureService {
089
090    private static final Log log = LogFactory.getLog(SignatureServiceImpl.class);
091
092    protected static final int SIGNATURE_FIELD_HEIGHT = 50;
093
094    protected static final int SIGNATURE_FIELD_WIDTH = 150;
095
096    protected static final int SIGNATURE_MARGIN = 10;
097
098    protected static final int PAGE_TO_SIGN = 1;
099
100    protected static final String XP_SIGNATURE = "signature";
101
102    protected static final String ALREADY_SIGNED_BY = "This document has already been signed by ";
103
104    protected static final String MIME_TYPE_PDF = "application/pdf";
105
106    /** From JODBasedConverter */
107    protected static final String PDFA1_PARAM = "PDF/A-1";
108
109    protected static final String FILE_CONTENT = "file:content";
110
111    protected static final String FILES_FILES = "files:files";
112
113    protected static final String FILES_FILE = "file";
114
115    protected static final String USER_EMAIL = "user:email";
116
117    protected final Map<String, SignatureDescriptor> signatureRegistryMap;
118
119    public SignatureServiceImpl() {
120        signatureRegistryMap = new HashMap<>();
121    }
122
123    @Override
124    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
125        if (XP_SIGNATURE.equals(extensionPoint)) {
126            SignatureDescriptor signatureDescriptor = (SignatureDescriptor) contribution;
127            if (!signatureDescriptor.getRemoveExtension()) {
128                signatureRegistryMap.put(signatureDescriptor.getId(), signatureDescriptor);
129            } else {
130                signatureRegistryMap.remove(signatureDescriptor.getId());
131            }
132        }
133    }
134
135    @Override
136    public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
137        if (XP_SIGNATURE.equals(extensionPoint)) {
138            SignatureDescriptor signatureDescriptor = (SignatureDescriptor) contribution;
139            if (!signatureDescriptor.getRemoveExtension()) {
140                signatureRegistryMap.remove(signatureDescriptor.getId());
141            }
142        }
143    }
144
145    //
146    // ----- SignatureService -----
147    //
148
149    @Override
150    public StatusWithBlob getSigningStatus(DocumentModel doc, DocumentModel user) {
151        if (doc == null) {
152            return new StatusWithBlob(UNSIGNABLE, null, null, null);
153        }
154        StatusWithBlob blobAndStatus = getSignedPdfBlobAndStatus(doc, user);
155        if (blobAndStatus != null) {
156            return blobAndStatus;
157        }
158        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
159        Blob blob;
160        if (mbh == null || (blob = mbh.getBlob()) == null) {
161            return new StatusWithBlob(UNSIGNABLE, null, null, null);
162        }
163        return new StatusWithBlob(UNSIGNED, blob, mbh, FILE_CONTENT);
164    }
165
166    protected int getSigningStatus(Blob pdfBlob, DocumentModel user) {
167        if (pdfBlob == null) {
168            return UNSIGNED;
169        }
170        List<X509Certificate> certificates = getCertificates(pdfBlob);
171        if (certificates.isEmpty()) {
172            return UNSIGNED;
173        }
174        if (user == null) {
175            return SIGNED_OTHER;
176        }
177        String email = (String) user.getPropertyValue(USER_EMAIL);
178        if (StringUtils.isEmpty(email)) {
179            return SIGNED_OTHER;
180        }
181        CertService certService = Framework.getLocalService(CertService.class);
182        for (X509Certificate certificate : certificates) {
183            String certEmail;
184            try {
185                certEmail = certService.getCertificateEmail(certificate);
186            } catch (CertException e) {
187                continue;
188            }
189            if (email.equals(certEmail)) {
190                return SIGNED_CURRENT;
191            }
192        }
193        return SIGNED_OTHER;
194    }
195
196    /**
197     * Finds the first signed PDF blob.
198     */
199    protected StatusWithBlob getSignedPdfBlobAndStatus(DocumentModel doc, DocumentModel user) {
200        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
201        if (mbh != null) {
202            Blob blob = mbh.getBlob();
203            if (blob != null && MIME_TYPE_PDF.equals(blob.getMimeType())) {
204                int status = getSigningStatus(blob, user);
205                if (status != UNSIGNED) {
206                    // TODO for File document it works, but for general
207                    // blob holders the path may be incorrect
208                    return new StatusWithBlob(status, blob, mbh, FILE_CONTENT);
209                }
210            }
211        }
212        @SuppressWarnings("unchecked")
213        List<Map<String, Serializable>> files = (List<Map<String, Serializable>>) doc.getPropertyValue(FILES_FILES);
214        int i = -1;
215        for (Map<String, Serializable> map : files) {
216            i++;
217            Blob blob = (Blob) map.get(FILES_FILE);
218            if (blob != null && MIME_TYPE_PDF.equals(blob.getMimeType())) {
219                int status = getSigningStatus(blob, user);
220                if (status != UNSIGNED) {
221                    String pathbase = FILES_FILES + "/" + i + "/";
222                    String path = pathbase + FILES_FILE;
223                    BlobHolder bh = new DocumentBlobHolder(doc, path);
224                    return new StatusWithBlob(status, blob, bh, path);
225                }
226            }
227        }
228        return null;
229    }
230
231    @Override
232    public Blob signDocument(DocumentModel doc, DocumentModel user, String keyPassword, String reason, boolean pdfa,
233            SigningDisposition disposition, String archiveFilename) {
234
235        StatusWithBlob blobAndStatus = getSignedPdfBlobAndStatus(doc, user);
236        if (blobAndStatus != null) {
237            // re-sign it
238            Blob signedBlob = signPDF(blobAndStatus.blob, doc, user, keyPassword, reason);
239            signedBlob.setFilename(blobAndStatus.blob.getFilename());
240            // replace the previous blob with a new one
241            blobAndStatus.blobHolder.setBlob(signedBlob);
242            return signedBlob;
243        }
244
245        Blob originalBlob;
246        BlobHolder mbh = doc.getAdapter(BlobHolder.class);
247        if (mbh == null || (originalBlob = mbh.getBlob()) == null) {
248            return null;
249        }
250
251        Blob pdfBlob;
252        if (MIME_TYPE_PDF.equals(originalBlob.getMimeType())) {
253            pdfBlob = originalBlob;
254        } else {
255            // convert to PDF or PDF/A first
256            ConversionService conversionService = Framework.getLocalService(ConversionService.class);
257            Map<String, Serializable> parameters = new HashMap<>();
258            if (pdfa) {
259                parameters.put(PDFA1_PARAM, Boolean.TRUE);
260            }
261            try {
262                BlobHolder holder = conversionService.convert("any2pdf", new SimpleBlobHolder(originalBlob),
263                        parameters);
264                pdfBlob = holder.getBlob();
265            } catch (ConversionException conversionException) {
266                throw new SignException(conversionException);
267            }
268        }
269
270        Blob signedBlob = signPDF(pdfBlob, doc, user, keyPassword, reason);
271        signedBlob.setFilename(FilenameUtils.getBaseName(originalBlob.getFilename()) + ".pdf");
272
273        Map<String, Serializable> map;
274        ListDiff listDiff;
275        switch (disposition) {
276        case REPLACE:
277            // replace main blob
278            mbh.setBlob(signedBlob);
279            break;
280        case ARCHIVE:
281            // archive as attachment
282            originalBlob.setFilename(archiveFilename);
283            map = new HashMap<>();
284            map.put(FILES_FILE, (Serializable) originalBlob);
285            listDiff = new ListDiff();
286            listDiff.add(map);
287            doc.setPropertyValue(FILES_FILES, listDiff);
288            // and replace main blob
289            mbh.setBlob(signedBlob);
290            break;
291        case ATTACH:
292            // set as first attachment
293            map = new HashMap<>();
294            map.put(FILES_FILE, (Serializable) signedBlob);
295            listDiff = new ListDiff();
296            listDiff.insert(0, map);
297            doc.setPropertyValue(FILES_FILES, listDiff);
298            break;
299        }
300
301        return signedBlob;
302    }
303
304    @Override
305    public Blob signPDF(Blob pdfBlob, DocumentModel doc, DocumentModel user, String keyPassword, String reason) {
306        CertService certService = Framework.getLocalService(CertService.class);
307        CUserService cUserService = Framework.getLocalService(CUserService.class);
308        try {
309            File outputFile = Framework.createTempFile("signed-", ".pdf");
310            Blob blob = Blobs.createBlob(outputFile, MIME_TYPE_PDF);
311            Framework.trackFile(outputFile, blob);
312
313            PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
314            List<X509Certificate> pdfCertificates = getCertificates(pdfReader);
315
316            // allows for multiple signatures
317            PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, new FileOutputStream(outputFile), '\0', null,
318                    true);
319
320            String userID = (String) user.getPropertyValue("user:username");
321            AliasWrapper alias = new AliasWrapper(userID);
322            KeyStore keystore = cUserService.getUserKeystore(userID, keyPassword);
323            Certificate certificate = certService.getCertificate(keystore, alias.getId(AliasType.CERT));
324            KeyPair keyPair = certService.getKeyPair(keystore, alias.getId(AliasType.KEY), alias.getId(AliasType.CERT),
325                    keyPassword);
326
327            if (certificatePresentInPDF(certificate, pdfCertificates)) {
328                X509Certificate userX509Certificate = (X509Certificate) certificate;
329                String message = ALREADY_SIGNED_BY + userX509Certificate.getSubjectDN();
330                log.debug(message);
331                throw new AlreadySignedException(message);
332            }
333
334            List<Certificate> certificates = new ArrayList<>();
335            certificates.add(certificate);
336
337            Certificate[] certChain = certificates.toArray(new Certificate[0]);
338            PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
339            pdfSignatureAppearance.setCrypto(keyPair.getPrivate(), certChain, null, PdfSignatureAppearance.SELF_SIGNED);
340            if (StringUtils.isBlank(reason)) {
341                reason = getSigningReason();
342            }
343            pdfSignatureAppearance.setVisibleSignature(getNextCertificatePosition(pdfReader, pdfCertificates), 1, null);
344            getSignatureAppearanceFactory().format(pdfSignatureAppearance, doc, userID, reason);
345
346            pdfStamper.close(); // closes the file
347
348            log.debug("File " + outputFile.getAbsolutePath() + " created and signed with " + reason);
349
350            return blob;
351        } catch (IOException | DocumentException | InstantiationException | IllegalAccessException e) {
352            throw new SignException(e);
353        } catch (IllegalArgumentException e) {
354            if (String.valueOf(e.getMessage()).contains("PdfReader not opened with owner password")) {
355                // iText PDF reading
356                throw new SignException("PDF is password-protected");
357            }
358            throw new SignException(e);
359        }
360    }
361
362    /**
363     * @since 5.8
364     * @return the signature layout. Default one if no contribution.
365     */
366    @Override
367    public SignatureLayout getSignatureLayout() {
368        for (SignatureDescriptor signatureDescriptor : signatureRegistryMap.values()) {
369            SignatureLayout signatureLayout = signatureDescriptor.getSignatureLayout();
370            if (signatureLayout != null) {
371                return signatureLayout;
372            }
373        }
374        return new SignatureDescriptor.SignatureLayout();
375    }
376
377    protected SignatureAppearanceFactory getSignatureAppearanceFactory()
378            throws InstantiationException, IllegalAccessException {
379        for (SignatureDescriptor signatureDescriptor : signatureRegistryMap.values()) {
380            return signatureDescriptor.getAppearanceFatory();
381        }
382        return new DefaultSignatureAppearanceFactory();
383    }
384
385    protected String getSigningReason() throws SignException {
386        for (SignatureDescriptor sd : signatureRegistryMap.values()) {
387            String reason = sd.getReason();
388            if (!StringUtils.isBlank(reason)) {
389                return reason;
390            }
391        }
392        throw new SignException("No default signing reason provided in configuration");
393    }
394
395    protected boolean certificatePresentInPDF(Certificate userCert, List<X509Certificate> pdfCertificates)
396            throws SignException {
397        X509Certificate xUserCert = (X509Certificate) userCert;
398        for (X509Certificate xcert : pdfCertificates) {
399            // matching certificate found
400            if (xcert.getSubjectX500Principal().equals(xUserCert.getSubjectX500Principal())) {
401                return true;
402            }
403        }
404        return false;
405    }
406
407    /**
408     * @since 5.8 Provides the position rectangle for the next certificate. An assumption is made that all previous
409     *        certificates in a given PDF were placed using the same technique and settings. New certificates are added
410     *        depending of signature layout contributed.
411     */
412    protected Rectangle getNextCertificatePosition(PdfReader pdfReader, List<X509Certificate> pdfCertificates)
413            throws SignException {
414        int numberOfSignatures = pdfCertificates.size();
415
416        Rectangle pageSize = pdfReader.getPageSize(PAGE_TO_SIGN);
417
418        // PDF size
419        float width = pageSize.getWidth();
420        float height = pageSize.getHeight();
421
422        // Signature size
423        float rectangleWidth = width / getSignatureLayout().getColumns();
424        float rectangeHeight = height / getSignatureLayout().getLines();
425
426        // Signature location
427        int column = numberOfSignatures % getSignatureLayout().getColumns() + getSignatureLayout().getStartColumn();
428        int line = numberOfSignatures / getSignatureLayout().getColumns() + getSignatureLayout().getStartLine();
429        if (column > getSignatureLayout().getColumns()) {
430            column = column % getSignatureLayout().getColumns();
431            line++;
432        }
433
434        // Skip rectangle display If number of signatures exceed free locations
435        // on pdf layout
436        if (line > getSignatureLayout().getLines()) {
437            return new Rectangle(0, 0, 0, 0);
438        }
439
440        // make smaller by page margin
441        float topRightX = rectangleWidth * column;
442        float bottomLeftY = height - rectangeHeight * line;
443        float bottomLeftX = topRightX - SIGNATURE_FIELD_WIDTH;
444        float topRightY = bottomLeftY + SIGNATURE_FIELD_HEIGHT;
445
446        // verify current position coordinates in case they were
447        // misconfigured
448        validatePageBounds(pdfReader, 1, bottomLeftX, true);
449        validatePageBounds(pdfReader, 1, bottomLeftY, false);
450        validatePageBounds(pdfReader, 1, topRightX, true);
451        validatePageBounds(pdfReader, 1, topRightY, false);
452
453        Rectangle positionRectangle = new Rectangle(bottomLeftX, bottomLeftY, topRightX, topRightY);
454
455        return positionRectangle;
456    }
457
458    /**
459     * Verifies that a provided value fits within the page bounds. If it does not, a sign exception is thrown. This is
460     * to verify externally configurable signature positioning.
461     *
462     * @param isHorizontal - if false, the current value is checked agains the vertical page dimension
463     */
464    protected void validatePageBounds(PdfReader pdfReader, int pageNo, float valueToCheck, boolean isHorizontal)
465            throws SignException {
466        if (valueToCheck < 0) {
467            String message = "The new signature position " + valueToCheck
468                    + " exceeds the page bounds. The position must be a positive number.";
469            log.debug(message);
470            throw new SignException(message);
471        }
472
473        Rectangle pageRectangle = pdfReader.getPageSize(pageNo);
474        if (isHorizontal && valueToCheck > pageRectangle.getRight()) {
475            String message = "The new signature position " + valueToCheck
476                    + " exceeds the horizontal page bounds. The page dimensions are: (" + pageRectangle + ").";
477            log.debug(message);
478            throw new SignException(message);
479        }
480        if (!isHorizontal && valueToCheck > pageRectangle.getTop()) {
481            String message = "The new signature position " + valueToCheck
482                    + " exceeds the vertical page bounds. The page dimensions are: (" + pageRectangle + ").";
483            log.debug(message);
484            throw new SignException(message);
485        }
486    }
487
488    @Override
489    public List<X509Certificate> getCertificates(DocumentModel doc) {
490        StatusWithBlob signedBlob = getSignedPdfBlobAndStatus(doc, null);
491        if (signedBlob == null) {
492            return Collections.emptyList();
493        }
494        return getCertificates(signedBlob.blob);
495    }
496
497    protected List<X509Certificate> getCertificates(Blob pdfBlob) throws SignException {
498        try {
499            PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
500            return getCertificates(pdfReader);
501        } catch (IOException e) {
502            String message = "";
503            if (e.getMessage().equals("PDF header signature not found.")) {
504                message = "PDF seems to be corrupted";
505            }
506            throw new SignException(message, e);
507        }
508    }
509
510    protected List<X509Certificate> getCertificates(PdfReader pdfReader) throws SignException {
511        List<X509Certificate> pdfCertificates = new ArrayList<>();
512        AcroFields acroFields = pdfReader.getAcroFields();
513        @SuppressWarnings("unchecked")
514        List<String> signatureNames = acroFields.getSignatureNames();
515        for (String signatureName : signatureNames) {
516            PdfPKCS7 pdfPKCS7 = acroFields.verifySignature(signatureName);
517            X509Certificate signingCertificate = pdfPKCS7.getSigningCertificate();
518            pdfCertificates.add(signingCertificate);
519        }
520        return pdfCertificates;
521    }
522
523}