acme.sh 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  1. #!/usr/bin/env bash
  2. VER=2.1.1
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [[ -z "$AGREEMENT" ]] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _info() {
  20. if [[ -z "$2" ]] ; then
  21. echo "[$(date)] $1"
  22. else
  23. echo "[$(date)] $1"="'$2'"
  24. fi
  25. }
  26. _err() {
  27. _info "$@" >&2
  28. return 1
  29. }
  30. _debug() {
  31. if [[ -z "$DEBUG" ]] ; then
  32. return
  33. fi
  34. _err "$@"
  35. return 0
  36. }
  37. _debug2() {
  38. if [[ "$DEBUG" -ge "2" ]] ; then
  39. _debug "$@"
  40. fi
  41. return
  42. }
  43. _exists() {
  44. cmd="$1"
  45. if [[ -z "$cmd" ]] ; then
  46. _err "Usage: _exists cmd"
  47. return 1
  48. fi
  49. command -v $cmd >/dev/null 2>&1
  50. ret="$?"
  51. _debug2 "$cmd exists=$ret"
  52. return $ret
  53. }
  54. _h2b() {
  55. hex=$(cat)
  56. i=1
  57. j=2
  58. while [ '1' ] ; do
  59. h=$(printf $hex | cut -c $i-$j)
  60. if [[ -z "$h" ]] ; then
  61. break;
  62. fi
  63. printf "\x$h"
  64. let "i+=2"
  65. let "j+=2"
  66. done
  67. }
  68. #options file
  69. _sed_i() {
  70. options="$1"
  71. filename="$2"
  72. if [[ -z "$filename" ]] ; then
  73. _err "Usage:_sed_i options filename"
  74. return 1
  75. fi
  76. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  77. _debug "Using sed -i"
  78. sed -i ""
  79. else
  80. _debug "No -i support in sed"
  81. text="$(cat $filename)"
  82. echo "$text" | sed "$options" > "$filename"
  83. fi
  84. }
  85. #Usage: file startline endline
  86. _getfile() {
  87. filename="$1"
  88. startline="$2"
  89. endline="$3"
  90. if [[ -z "$endline" ]] ; then
  91. _err "Usage: file startline endline"
  92. return 1
  93. fi
  94. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  95. if [[ -z "$i" ]] ; then
  96. _err "Can not find start line: $startline"
  97. return 1
  98. fi
  99. let "i+=1"
  100. _debug i $i
  101. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  102. if [[ -z "$j" ]] ; then
  103. _err "Can not find end line: $endline"
  104. return 1
  105. fi
  106. let "j-=1"
  107. _debug j $j
  108. sed -n $i,${j}p "$filename"
  109. }
  110. #Usage: multiline
  111. _base64() {
  112. if [[ "$1" ]] ; then
  113. openssl base64 -e
  114. else
  115. openssl base64 -e | tr -d '\r\n'
  116. fi
  117. }
  118. #Usage: multiline
  119. _dbase64() {
  120. if [[ "$1" ]] ; then
  121. openssl base64 -d -A
  122. else
  123. openssl base64 -d
  124. fi
  125. }
  126. #Usage: hashalg
  127. #Output Base64-encoded digest
  128. _digest() {
  129. alg="$1"
  130. if [[ -z "$alg" ]] ; then
  131. _err "Usage: _digest hashalg"
  132. return 1
  133. fi
  134. if [[ "$alg" == "sha256" ]] ; then
  135. openssl dgst -sha256 -binary | _base64
  136. else
  137. _err "$alg is not supported yet"
  138. return 1
  139. fi
  140. }
  141. #Usage: keyfile hashalg
  142. #Output: Base64-encoded signature value
  143. _sign() {
  144. keyfile="$1"
  145. alg="$2"
  146. if [[ -z "$alg" ]] ; then
  147. _err "Usage: _sign keyfile hashalg"
  148. return 1
  149. fi
  150. if [[ "$alg" == "sha256" ]] ; then
  151. openssl dgst -sha256 -sign "$keyfile" | _base64
  152. else
  153. _err "$alg is not supported yet"
  154. return 1
  155. fi
  156. }
  157. _ss() {
  158. _port="$1"
  159. if _exists "ss" ; then
  160. _debug "Using: ss"
  161. ss -ntpl | grep :$_port" "
  162. return 0
  163. fi
  164. if _exists "netstat" ; then
  165. _debug "Using: netstat"
  166. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  167. #for windows version netstat tool
  168. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  169. else
  170. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  171. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  172. else
  173. netstat -ntpl | grep :$_port" "
  174. fi
  175. fi
  176. return 0
  177. fi
  178. return 1
  179. }
  180. toPkcs() {
  181. domain="$1"
  182. pfxPassword="$2"
  183. if [[ -z "$domain" ]] ; then
  184. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  185. return 1
  186. fi
  187. _initpath "$domain"
  188. if [[ "$pfxPassword" ]] ; then
  189. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  190. else
  191. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  192. fi
  193. if [[ "$?" == "0" ]] ; then
  194. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  195. fi
  196. }
  197. #domain [2048]
  198. createAccountKey() {
  199. _info "Creating account key"
  200. if [[ -z "$1" ]] ; then
  201. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  202. return
  203. fi
  204. account=$1
  205. length=$2
  206. _debug account "$account"
  207. _debug length "$length"
  208. if [[ "$length" == "ec-"* ]] ; then
  209. length=2048
  210. fi
  211. if [[ -z "$2" ]] || [[ "$2" == "no" ]] ; then
  212. _info "Use default length 2048"
  213. length=2048
  214. fi
  215. _initpath
  216. if [[ -f "$ACCOUNT_KEY_PATH" ]] ; then
  217. _info "Account key exists, skip"
  218. return
  219. else
  220. #generate account key
  221. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  222. fi
  223. }
  224. #domain length
  225. createDomainKey() {
  226. _info "Creating domain key"
  227. if [[ -z "$1" ]] ; then
  228. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  229. return
  230. fi
  231. domain=$1
  232. length=$2
  233. isec=""
  234. if [[ "$length" == "ec-"* ]] ; then
  235. isec="1"
  236. length=$(printf $length | cut -d '-' -f 2-100)
  237. eccname="$length"
  238. fi
  239. if [[ -z "$length" ]] ; then
  240. if [[ "$isec" ]] ; then
  241. length=256
  242. else
  243. length=2048
  244. fi
  245. fi
  246. _info "Use length $length"
  247. if [[ "$isec" ]] ; then
  248. if [[ "$length" == "256" ]] ; then
  249. eccname="prime256v1"
  250. fi
  251. if [[ "$length" == "384" ]] ; then
  252. eccname="secp384r1"
  253. fi
  254. if [[ "$length" == "521" ]] ; then
  255. eccname="secp521r1"
  256. fi
  257. _info "Using ec name: $eccname"
  258. fi
  259. _initpath $domain
  260. if [[ ! -f "$CERT_KEY_PATH" ]] || ( [[ "$FORCE" ]] && ! [[ "$IS_RENEW" ]] ); then
  261. #generate account key
  262. if [[ "$isec" ]] ; then
  263. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  264. else
  265. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  266. fi
  267. else
  268. if [[ "$IS_RENEW" ]] ; then
  269. _info "Domain key exists, skip"
  270. return 0
  271. else
  272. _err "Domain key exists, do you want to overwrite the key?"
  273. _err "Add '--force', and try again."
  274. return 1
  275. fi
  276. fi
  277. }
  278. # domain domainlist
  279. createCSR() {
  280. _info "Creating csr"
  281. if [[ -z "$1" ]] ; then
  282. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  283. return
  284. fi
  285. domain=$1
  286. _initpath $domain
  287. domainlist=$2
  288. if [[ -f "$CSR_PATH" ]] && [[ "$IS_RENEW" ]] && [[ -z "$FORCE" ]]; then
  289. _info "CSR exists, skip"
  290. return
  291. fi
  292. if [[ -z "$domainlist" ]] || [[ "$domainlist" == "no" ]]; then
  293. #single domain
  294. _info "Single domain" $domain
  295. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  296. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  297. else
  298. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  299. #multi
  300. _info "Multi domain" "$alt"
  301. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  302. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  303. fi
  304. }
  305. _urlencode() {
  306. __n=$(cat)
  307. echo $__n | tr '/+' '_-' | tr -d '= '
  308. }
  309. _time2str() {
  310. #BSD
  311. if date -u -d@$1 2>/dev/null ; then
  312. return
  313. fi
  314. #Linux
  315. if date -u -r $1 2>/dev/null ; then
  316. return
  317. fi
  318. }
  319. _stat() {
  320. #Linux
  321. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  322. return
  323. fi
  324. #BSD
  325. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  326. return
  327. fi
  328. }
  329. #keyfile
  330. _calcjwk() {
  331. keyfile="$1"
  332. if [[ -z "$keyfile" ]] ; then
  333. _err "Usage: _calcjwk keyfile"
  334. return 1
  335. fi
  336. EC_SIGN=""
  337. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  338. _debug "RSA key"
  339. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  340. if [[ "${#pub_exp}" == "5" ]] ; then
  341. pub_exp=0$pub_exp
  342. fi
  343. _debug2 pub_exp "$pub_exp"
  344. e=$(echo $pub_exp | _h2b | _base64)
  345. _debug2 e "$e"
  346. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  347. n=$(echo $modulus| _h2b | _base64 | _urlencode )
  348. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  349. _debug2 jwk "$jwk"
  350. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  351. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  352. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  353. _debug "EC key"
  354. EC_SIGN="1"
  355. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  356. _debug2 crv $crv
  357. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  358. _debug2 pubi $pubi
  359. let "pubi=pubi+1"
  360. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  361. _debug2 pubj $pubj
  362. let "pubj=pubj-1"
  363. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  364. _debug2 pubtext "$pubtext"
  365. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  366. let "xlen=xlen/4"
  367. _debug2 xlen $xlen
  368. let "xend=xlen+1"
  369. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  370. _debug2 x $x
  371. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  372. _debug2 x64 $x64
  373. let "xend+=1"
  374. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  375. _debug2 y $y
  376. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  377. _debug2 y64 $y64
  378. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  379. _debug2 jwk "$jwk"
  380. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  381. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  382. else
  383. _err "Only RSA or EC key is supported."
  384. return 1
  385. fi
  386. _debug2 HEADER "$HEADER"
  387. }
  388. # body url [needbase64]
  389. _post() {
  390. body="$1"
  391. url="$2"
  392. needbase64="$3"
  393. if _exists "curl" ; then
  394. CURL="$CURL --dump-header $HTTP_HEADER "
  395. if [[ "$needbase64" ]] ; then
  396. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  397. else
  398. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  399. fi
  400. else
  401. if [[ "$needbase64" ]] ; then
  402. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  403. else
  404. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  405. fi
  406. _sed_i "s/^ *//g" "$HTTP_HEADER"
  407. fi
  408. echo -n "$response"
  409. }
  410. # url getheader
  411. _get() {
  412. url="$1"
  413. onlyheader="$2"
  414. _debug url $url
  415. if _exists "curl" ; then
  416. if [[ "$onlyheader" ]] ; then
  417. $CURL -I -A "User-Agent: $USER_AGENT" $url
  418. else
  419. $CURL -A "User-Agent: $USER_AGENT" $url
  420. fi
  421. else
  422. _debug "WGET" "$WGET"
  423. if [[ "$onlyheader" ]] ; then
  424. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  425. else
  426. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  427. fi
  428. fi
  429. ret=$?
  430. return $ret
  431. }
  432. # url payload needbase64 keyfile
  433. _send_signed_request() {
  434. url=$1
  435. payload=$2
  436. needbase64=$3
  437. keyfile=$4
  438. if [[ -z "$keyfile" ]] ; then
  439. keyfile="$ACCOUNT_KEY_PATH"
  440. fi
  441. _debug url $url
  442. _debug payload "$payload"
  443. if ! _calcjwk "$keyfile" ; then
  444. return 1
  445. fi
  446. payload64=$(echo -n $payload | _base64 | _urlencode)
  447. _debug2 payload64 $payload64
  448. nonceurl="$API/directory"
  449. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  450. _debug nonce "$nonce"
  451. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  452. _debug2 protected "$protected"
  453. protected64="$(printf "$protected" | _base64 | _urlencode)"
  454. _debug2 protected64 "$protected64"
  455. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  456. _debug2 sig "$sig"
  457. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  458. _debug2 body "$body"
  459. response="$(_post "$body" $url "$needbase64" )"
  460. responseHeaders="$(cat $HTTP_HEADER)"
  461. _debug2 responseHeaders "$responseHeaders"
  462. _debug2 response "$response"
  463. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  464. _debug code $code
  465. }
  466. #setopt "file" "opt" "=" "value" [";"]
  467. _setopt() {
  468. __conf="$1"
  469. __opt="$2"
  470. __sep="$3"
  471. __val="$4"
  472. __end="$5"
  473. if [[ -z "$__opt" ]] ; then
  474. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  475. return
  476. fi
  477. if [[ ! -f "$__conf" ]] ; then
  478. touch "$__conf"
  479. fi
  480. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  481. _debug2 OK
  482. if [[ "$__val" == *"&"* ]] ; then
  483. __val="$(echo $__val | sed 's/&/\\&/g')"
  484. fi
  485. text="$(cat $__conf)"
  486. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  487. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  488. if [[ "$__val" == *"&"* ]] ; then
  489. __val="$(echo $__val | sed 's/&/\\&/g')"
  490. fi
  491. text="$(cat $__conf)"
  492. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  493. else
  494. _debug2 APP
  495. echo "$__opt$__sep$__val$__end" >> "$__conf"
  496. fi
  497. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  498. }
  499. #_savedomainconf key value
  500. #save to domain.conf
  501. _savedomainconf() {
  502. key="$1"
  503. value="$2"
  504. if [[ "$DOMAIN_CONF" ]] ; then
  505. _setopt $DOMAIN_CONF "$key" "=" "$value"
  506. else
  507. _err "DOMAIN_CONF is empty, can not save $key=$value"
  508. fi
  509. }
  510. #_saveaccountconf key value
  511. _saveaccountconf() {
  512. key="$1"
  513. value="$2"
  514. if [[ "$ACCOUNT_CONF_PATH" ]] ; then
  515. _setopt $ACCOUNT_CONF_PATH "$key" "=" "\"$value\""
  516. else
  517. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  518. fi
  519. }
  520. _startserver() {
  521. content="$1"
  522. _debug "startserver: $$"
  523. nchelp="$(nc -h 2>&1)"
  524. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  525. _NC="nc -q 1 -l"
  526. else
  527. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  528. _NC="nc -c -l"
  529. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  530. _NC="nc -N -l"
  531. else
  532. _NC="nc -l"
  533. fi
  534. fi
  535. _debug "_NC" "$_NC"
  536. # while true ; do
  537. if [[ "$DEBUG" ]] ; then
  538. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  539. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  540. fi
  541. else
  542. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  543. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  544. fi
  545. fi
  546. if [[ "$?" != "0" ]] ; then
  547. _err "nc listen error."
  548. exit 1
  549. fi
  550. # done
  551. }
  552. _stopserver(){
  553. pid="$1"
  554. _debug "pid" "$pid"
  555. if [[ -z "$pid" ]] ; then
  556. return
  557. fi
  558. if [[ "$(ps | grep "$pid")" ]] ; then
  559. _debug "Found proc process, kill it."
  560. kill -s 9 $pid > /dev/null
  561. fi
  562. for ncid in $(echo $(ps | grep nc) | cut -d " " -f 1) ; do
  563. _debug "kill $ncid"
  564. kill -s 9 $ncid > /dev/null
  565. done
  566. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  567. }
  568. _initpath() {
  569. if [[ -z "$LE_WORKING_DIR" ]] ; then
  570. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  571. fi
  572. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  573. if [[ -z "$ACCOUNT_CONF_PATH" ]] ; then
  574. if [[ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]] ; then
  575. source "$_DEFAULT_ACCOUNT_CONF_PATH"
  576. fi
  577. fi
  578. if [[ -z "$ACCOUNT_CONF_PATH" ]] ; then
  579. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  580. fi
  581. if [[ -f "$ACCOUNT_CONF_PATH" ]] ; then
  582. source "$ACCOUNT_CONF_PATH"
  583. fi
  584. if [[ "$IN_CRON" ]] ; then
  585. if [[ ! "$_USER_PATH_EXPORTED" ]] ; then
  586. _USER_PATH_EXPORTED=1
  587. export PATH="$USER_PATH:$PATH"
  588. fi
  589. fi
  590. if [[ -z "$API" ]] ; then
  591. if [[ -z "$STAGE" ]] ; then
  592. API="$DEFAULT_CA"
  593. else
  594. API="$STAGE_CA"
  595. _info "Using stage api:$API"
  596. fi
  597. fi
  598. if [[ -z "$ACME_DIR" ]] ; then
  599. ACME_DIR="/home/.acme"
  600. fi
  601. if [[ -z "$APACHE_CONF_BACKUP_DIR" ]] ; then
  602. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  603. fi
  604. if [[ -z "$USER_AGENT" ]] ; then
  605. USER_AGENT="$DEFAULT_USER_AGENT"
  606. fi
  607. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  608. WGET="wget -q"
  609. if [[ "$DEBUG" -ge "2" ]] ; then
  610. WGET="$WGET -d "
  611. fi
  612. dp="$LE_WORKING_DIR/curl.dump"
  613. CURL="curl -L --silent"
  614. if [[ "$DEBUG" -ge "2" ]] ; then
  615. CURL="$CURL -L --trace-ascii $dp "
  616. fi
  617. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  618. if [[ -z "$ACCOUNT_KEY_PATH" ]] ; then
  619. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  620. fi
  621. domain="$1"
  622. if [[ -z "$domain" ]] ; then
  623. return 0
  624. fi
  625. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  626. if [[ -z "$CERT_HOME" ]] ; then
  627. CERT_HOME="$_DEFAULT_CERT_HOME"
  628. fi
  629. domainhome="$CERT_HOME/$domain"
  630. mkdir -p "$domainhome"
  631. if [[ -z "$DOMAIN_PATH" ]] ; then
  632. DOMAIN_PATH="$domainhome"
  633. fi
  634. if [[ -z "$DOMAIN_CONF" ]] ; then
  635. DOMAIN_CONF="$domainhome/$domain.conf"
  636. fi
  637. if [[ -z "$DOMAIN_SSL_CONF" ]] ; then
  638. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  639. fi
  640. if [[ -z "$CSR_PATH" ]] ; then
  641. CSR_PATH="$domainhome/$domain.csr"
  642. fi
  643. if [[ -z "$CERT_KEY_PATH" ]] ; then
  644. CERT_KEY_PATH="$domainhome/$domain.key"
  645. fi
  646. if [[ -z "$CERT_PATH" ]] ; then
  647. CERT_PATH="$domainhome/$domain.cer"
  648. fi
  649. if [[ -z "$CA_CERT_PATH" ]] ; then
  650. CA_CERT_PATH="$domainhome/ca.cer"
  651. fi
  652. if [[ -z "$CERT_FULLCHAIN_PATH" ]] ; then
  653. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  654. fi
  655. if [[ -z "$CERT_PFX_PATH" ]] ; then
  656. CERT_PFX_PATH="$domainhome/$domain.pfx"
  657. fi
  658. }
  659. _apachePath() {
  660. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  661. if [[ "$httpdconfname" == '/'* ]] ; then
  662. httpdconf="$httpdconfname"
  663. httpdconfname="$(basename $httpdconfname)"
  664. else
  665. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  666. httpdconf="$httpdroot/$httpdconfname"
  667. fi
  668. if [[ ! -f $httpdconf ]] ; then
  669. _err "Apache Config file not found" $httpdconf
  670. return 1
  671. fi
  672. return 0
  673. }
  674. _restoreApache() {
  675. if [[ -z "$usingApache" ]] ; then
  676. return 0
  677. fi
  678. _initpath
  679. if ! _apachePath ; then
  680. return 1
  681. fi
  682. if [[ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]] ; then
  683. _debug "No config file to restore."
  684. return 0
  685. fi
  686. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  687. _debug "Restored: $httpdconf."
  688. if ! apachectl -t ; then
  689. _err "Sorry, restore apache config error, please contact me."
  690. return 1;
  691. fi
  692. _debug "Restored successfully."
  693. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  694. return 0
  695. }
  696. _setApache() {
  697. _initpath
  698. if ! _apachePath ; then
  699. return 1
  700. fi
  701. #backup the conf
  702. _debug "Backup apache config file" $httpdconf
  703. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  704. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  705. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  706. _info "The backup file will be deleted on sucess, just forget it."
  707. #add alias
  708. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  709. _debug "apacheVer" "$apacheVer"
  710. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  711. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  712. if [[ "$apacheVer" ]] && [[ "$apacheMajer" -ge "2" ]] && [[ "$apacheMinor" -ge "4" ]] ; then
  713. echo "
  714. Alias /.well-known/acme-challenge $ACME_DIR
  715. <Directory $ACME_DIR >
  716. Require all granted
  717. </Directory>
  718. " >> $httpdconf
  719. else
  720. echo "
  721. Alias /.well-known/acme-challenge $ACME_DIR
  722. <Directory $ACME_DIR >
  723. Order allow,deny
  724. Allow from all
  725. </Directory>
  726. " >> $httpdconf
  727. fi
  728. if ! apachectl -t ; then
  729. _err "Sorry, apache config error, please contact me."
  730. _restoreApache
  731. return 1;
  732. fi
  733. if [[ ! -d "$ACME_DIR" ]] ; then
  734. mkdir -p "$ACME_DIR"
  735. chmod 755 "$ACME_DIR"
  736. fi
  737. if ! apachectl graceful ; then
  738. _err "Sorry, apachectl graceful error, please contact me."
  739. _restoreApache
  740. return 1;
  741. fi
  742. usingApache="1"
  743. return 0
  744. }
  745. _clearup() {
  746. _stopserver $serverproc
  747. serverproc=""
  748. _restoreApache
  749. }
  750. # webroot removelevel tokenfile
  751. _clearupwebbroot() {
  752. __webroot="$1"
  753. if [[ -z "$__webroot" ]] ; then
  754. _debug "no webroot specified, skip"
  755. return 0
  756. fi
  757. if [[ "$2" == '1' ]] ; then
  758. _debug "remove $__webroot/.well-known"
  759. rm -rf "$__webroot/.well-known"
  760. elif [[ "$2" == '2' ]] ; then
  761. _debug "remove $__webroot/.well-known/acme-challenge"
  762. rm -rf "$__webroot/.well-known/acme-challenge"
  763. elif [[ "$2" == '3' ]] ; then
  764. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  765. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  766. else
  767. _info "Skip for removelevel:$2"
  768. fi
  769. return 0
  770. }
  771. issue() {
  772. if [[ -z "$2" ]] ; then
  773. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  774. return 1
  775. fi
  776. Le_Webroot="$1"
  777. Le_Domain="$2"
  778. Le_Alt="$3"
  779. Le_Keylength="$4"
  780. Le_RealCertPath="$5"
  781. Le_RealKeyPath="$6"
  782. Le_RealCACertPath="$7"
  783. Le_ReloadCmd="$8"
  784. Le_RealFullChainPath="$9"
  785. _initpath $Le_Domain
  786. if [[ -f "$DOMAIN_CONF" ]] ; then
  787. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  788. if [[ -z "$FORCE" ]] && [[ "$Le_NextRenewTime" ]] && [[ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ]] ; then
  789. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  790. return 2
  791. fi
  792. fi
  793. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  794. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  795. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  796. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  797. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  798. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  799. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  800. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  801. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  802. if [[ "$Le_Alt" == "no" ]] ; then
  803. Le_Alt=""
  804. fi
  805. if [[ "$Le_Keylength" == "no" ]] ; then
  806. Le_Keylength=""
  807. fi
  808. if [[ "$Le_RealCertPath" == "no" ]] ; then
  809. Le_RealCertPath=""
  810. fi
  811. if [[ "$Le_RealKeyPath" == "no" ]] ; then
  812. Le_RealKeyPath=""
  813. fi
  814. if [[ "$Le_RealCACertPath" == "no" ]] ; then
  815. Le_RealCACertPath=""
  816. fi
  817. if [[ "$Le_ReloadCmd" == "no" ]] ; then
  818. Le_ReloadCmd=""
  819. fi
  820. if [[ "$Le_RealFullChainPath" == "no" ]] ; then
  821. Le_RealFullChainPath=""
  822. fi
  823. if [[ "$Le_Webroot" == *"no"* ]] ; then
  824. _info "Standalone mode."
  825. if ! _exists "nc" ; then
  826. _err "Please install netcat(nc) tools first."
  827. return 1
  828. fi
  829. if [[ -z "$Le_HTTPPort" ]] ; then
  830. Le_HTTPPort=80
  831. fi
  832. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  833. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  834. if [[ "$netprc" ]] ; then
  835. _err "$netprc"
  836. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  837. _err "Please stop it first"
  838. return 1
  839. fi
  840. fi
  841. if [[ "$Le_Webroot" == *"apache"* ]] ; then
  842. if ! _setApache ; then
  843. _err "set up apache error. Report error to me."
  844. return 1
  845. fi
  846. else
  847. usingApache=""
  848. fi
  849. if [[ ! -f "$ACCOUNT_KEY_PATH" ]] ; then
  850. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  851. _err "Create account key error."
  852. if [[ "$usingApache" ]] ; then
  853. _restoreApache
  854. fi
  855. return 1
  856. fi
  857. fi
  858. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  859. if [[ "$usingApache" ]] ; then
  860. _restoreApache
  861. fi
  862. return 1
  863. fi
  864. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  865. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  866. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  867. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  868. if [[ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ]] ; then
  869. _info "Registering account"
  870. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  871. if [[ "$ACCOUNT_EMAIL" ]] ; then
  872. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  873. fi
  874. _send_signed_request "$API/acme/new-reg" "$regjson"
  875. if [[ "$code" == "" ]] || [[ "$code" == '201' ]] ; then
  876. _info "Registered"
  877. echo $response > $LE_WORKING_DIR/account.json
  878. elif [[ "$code" == '409' ]] ; then
  879. _info "Already registered"
  880. else
  881. _err "Register account Error: $response"
  882. _clearup
  883. return 1
  884. fi
  885. ACCOUNT_KEY_HASH="$accountkeyhash"
  886. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  887. else
  888. _info "Skip register account key"
  889. fi
  890. if [[ ! -f "$CERT_KEY_PATH" ]] ; then
  891. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  892. _err "Create domain key error."
  893. _clearup
  894. return 1
  895. fi
  896. fi
  897. if ! createCSR $Le_Domain $Le_Alt ; then
  898. _err "Create CSR error."
  899. _clearup
  900. return 1
  901. fi
  902. vlist="$Le_Vlist"
  903. # verify each domain
  904. _info "Verify each domain"
  905. sep='#'
  906. if [[ -z "$vlist" ]] ; then
  907. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  908. _index=1
  909. _currentRoot=""
  910. for d in $alldomains
  911. do
  912. _info "Getting webroot for domain" $d
  913. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  914. _debug _w "$_w"
  915. if [[ "$_w" ]] ; then
  916. _currentRoot="$_w"
  917. fi
  918. _debug "_currentRoot" "$_currentRoot"
  919. let "_index+=1"
  920. vtype="$VTYPE_HTTP"
  921. if [[ "$_currentRoot" == "dns"* ]] ; then
  922. vtype="$VTYPE_DNS"
  923. fi
  924. _info "Getting token for domain" $d
  925. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  926. if [[ ! -z "$code" ]] && [[ ! "$code" == '201' ]] ; then
  927. _err "new-authz error: $response"
  928. _clearup
  929. return 1
  930. fi
  931. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  932. _debug entry "$entry"
  933. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  934. _debug token $token
  935. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  936. _debug uri $uri
  937. keyauthorization="$token.$thumbprint"
  938. _debug keyauthorization "$keyauthorization"
  939. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  940. _debug dvlist "$dvlist"
  941. vlist="$vlist$dvlist,"
  942. done
  943. #add entry
  944. dnsadded=""
  945. ventries=$(echo "$vlist" | tr ',' ' ' )
  946. for ventry in $ventries
  947. do
  948. d=$(echo $ventry | cut -d $sep -f 1)
  949. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  950. vtype=$(echo $ventry | cut -d $sep -f 4)
  951. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  952. if [[ "$vtype" == "$VTYPE_DNS" ]] ; then
  953. dnsadded='0'
  954. txtdomain="_acme-challenge.$d"
  955. _debug txtdomain "$txtdomain"
  956. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  957. _debug txt "$txt"
  958. #dns
  959. #1. check use api
  960. d_api=""
  961. if [[ -f "$LE_WORKING_DIR/$d/$_currentRoot" ]] ; then
  962. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  963. elif [[ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ]] ; then
  964. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  965. elif [[ -f "$LE_WORKING_DIR/$_currentRoot" ]] ; then
  966. d_api="$LE_WORKING_DIR/$_currentRoot"
  967. elif [[ -f "$LE_WORKING_DIR/$_currentRoot.sh" ]] ; then
  968. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  969. elif [[ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ]] ; then
  970. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  971. elif [[ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ]] ; then
  972. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  973. fi
  974. _debug d_api "$d_api"
  975. if [[ "$d_api" ]] ; then
  976. _info "Found domain api file: $d_api"
  977. else
  978. _err "Add the following TXT record:"
  979. _err "Domain: $txtdomain"
  980. _err "TXT value: $txt"
  981. _err "Please be aware that you prepend _acme-challenge. before your domain"
  982. _err "so the resulting subdomain will be: $txtdomain"
  983. continue
  984. fi
  985. (
  986. if ! source $d_api ; then
  987. _err "Load file $d_api error. Please check your api file and try again."
  988. return 1
  989. fi
  990. addcommand="$_currentRoot-add"
  991. if ! _exists $addcommand ; then
  992. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  993. return 1
  994. fi
  995. if ! $addcommand $txtdomain $txt ; then
  996. _err "Error add txt for domain:$txtdomain"
  997. return 1
  998. fi
  999. )
  1000. if [[ "$?" != "0" ]] ; then
  1001. _clearup
  1002. return 1
  1003. fi
  1004. dnsadded='1'
  1005. fi
  1006. done
  1007. if [[ "$dnsadded" == '0' ]] ; then
  1008. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  1009. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1010. _err "Please add the TXT records to the domains, and retry again."
  1011. _clearup
  1012. return 1
  1013. fi
  1014. fi
  1015. if [[ "$dnsadded" == '1' ]] ; then
  1016. _info "Sleep 60 seconds for the txt records to take effect"
  1017. sleep 60
  1018. fi
  1019. _debug "ok, let's start to verify"
  1020. ventries=$(echo "$vlist" | tr ',' ' ' )
  1021. for ventry in $ventries
  1022. do
  1023. d=$(echo $ventry | cut -d $sep -f 1)
  1024. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1025. uri=$(echo $ventry | cut -d $sep -f 3)
  1026. vtype=$(echo $ventry | cut -d $sep -f 4)
  1027. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1028. _info "Verifying:$d"
  1029. _debug "d" "$d"
  1030. _debug "keyauthorization" "$keyauthorization"
  1031. _debug "uri" "$uri"
  1032. removelevel=""
  1033. token=""
  1034. _debug "_currentRoot" "$_currentRoot"
  1035. if [[ "$vtype" == "$VTYPE_HTTP" ]] ; then
  1036. if [[ "$_currentRoot" == "no" ]] ; then
  1037. _info "Standalone mode server"
  1038. _startserver "$keyauthorization" &
  1039. if [[ "$?" != "0" ]] ; then
  1040. _clearup
  1041. return 1
  1042. fi
  1043. serverproc="$!"
  1044. sleep 2
  1045. _debug serverproc $serverproc
  1046. else
  1047. if [[ "$_currentRoot" == "apache" ]] ; then
  1048. wellknown_path="$ACME_DIR"
  1049. else
  1050. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1051. if [[ ! -d "$_currentRoot/.well-known" ]] ; then
  1052. removelevel='1'
  1053. elif [[ ! -d "$_currentRoot/.well-known/acme-challenge" ]] ; then
  1054. removelevel='2'
  1055. else
  1056. removelevel='3'
  1057. fi
  1058. fi
  1059. _debug wellknown_path "$wellknown_path"
  1060. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  1061. _debug "writing token:$token to $wellknown_path/$token"
  1062. mkdir -p "$wellknown_path"
  1063. echo -n "$keyauthorization" > "$wellknown_path/$token"
  1064. if [[ ! "$usingApache" ]] ; then
  1065. webroot_owner=$(_stat $_currentRoot)
  1066. _debug "Changing owner/group of .well-known to $webroot_owner"
  1067. chown -R $webroot_owner "$_currentRoot/.well-known"
  1068. fi
  1069. fi
  1070. fi
  1071. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1072. if [[ ! -z "$code" ]] && [[ ! "$code" == '202' ]] ; then
  1073. _err "$d:Challenge error: $response"
  1074. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1075. _clearup
  1076. return 1
  1077. fi
  1078. waittimes=0
  1079. if [[ -z "$MAX_RETRY_TIMES" ]] ; then
  1080. MAX_RETRY_TIMES=30
  1081. fi
  1082. while [[ "1" ]] ; do
  1083. let "waittimes+=1"
  1084. if [[ "$waittimes" -ge "$MAX_RETRY_TIMES" ]] ; then
  1085. _err "$d:Timeout"
  1086. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1087. _clearup
  1088. return 1
  1089. fi
  1090. _debug "sleep 5 secs to verify"
  1091. sleep 5
  1092. _debug "checking"
  1093. response="$(_get $uri)"
  1094. if [[ "$?" != "0" ]] ; then
  1095. _err "$d:Verify error:$response"
  1096. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1097. _clearup
  1098. return 1
  1099. fi
  1100. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1101. if [[ "$status" == "valid" ]] ; then
  1102. _info "Success"
  1103. _stopserver $serverproc
  1104. serverproc=""
  1105. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1106. break;
  1107. fi
  1108. if [[ "$status" == "invalid" ]] ; then
  1109. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1110. _err "$d:Verify error:$error"
  1111. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1112. _clearup
  1113. return 1;
  1114. fi
  1115. if [[ "$status" == "pending" ]] ; then
  1116. _info "Pending"
  1117. else
  1118. _err "$d:Verify error:$response"
  1119. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1120. _clearup
  1121. return 1
  1122. fi
  1123. done
  1124. done
  1125. _clearup
  1126. _info "Verify finished, start to sign."
  1127. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1128. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1129. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1130. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1131. if [[ "$Le_LinkCert" ]] ; then
  1132. echo "$BEGIN_CERT" > "$CERT_PATH"
  1133. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1134. echo "$END_CERT" >> "$CERT_PATH"
  1135. _info "Cert success."
  1136. cat "$CERT_PATH"
  1137. _info "Your cert is in $CERT_PATH"
  1138. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1139. if [[ ! "$USER_PATH" ]] || [[ ! "$IN_CRON" ]] ; then
  1140. USER_PATH="$PATH"
  1141. _saveaccountconf "USER_PATH" "$USER_PATH"
  1142. fi
  1143. fi
  1144. if [[ -z "$Le_LinkCert" ]] ; then
  1145. response="$(echo $response | _dbase64 "multiline" )"
  1146. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1147. return 1
  1148. fi
  1149. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1150. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1151. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1152. if [[ "$Le_LinkIssuer" ]] ; then
  1153. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1154. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1155. echo "$END_CERT" >> "$CA_CERT_PATH"
  1156. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1157. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1158. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1159. fi
  1160. Le_CertCreateTime=$(date -u "+%s")
  1161. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1162. Le_CertCreateTimeStr=$(date -u )
  1163. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1164. if [[ -z "$Le_RenewalDays" ]] || [[ "$Le_RenewalDays" -lt "0" ]] || [[ "$Le_RenewalDays" -gt "80" ]] ; then
  1165. Le_RenewalDays=80
  1166. fi
  1167. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1168. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  1169. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1170. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1171. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1172. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1173. }
  1174. renew() {
  1175. Le_Domain="$1"
  1176. if [[ -z "$Le_Domain" ]] ; then
  1177. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1178. return 1
  1179. fi
  1180. _initpath $Le_Domain
  1181. if [[ ! -f "$DOMAIN_CONF" ]] ; then
  1182. _info "$Le_Domain is not a issued domain, skip."
  1183. return 0;
  1184. fi
  1185. source "$DOMAIN_CONF"
  1186. if [[ -z "$FORCE" ]] && [[ "$Le_NextRenewTime" ]] && [[ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ]] ; then
  1187. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1188. return 2
  1189. fi
  1190. IS_RENEW="1"
  1191. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1192. local res=$?
  1193. IS_RENEW=""
  1194. return $res
  1195. }
  1196. renewAll() {
  1197. _initpath
  1198. _info "renewAll"
  1199. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1200. d=$(echo $d | cut -d '/' -f 1)
  1201. _info "renew $d"
  1202. Le_LinkCert=""
  1203. Le_Domain=""
  1204. Le_Alt="no"
  1205. Le_Webroot=""
  1206. Le_Keylength=""
  1207. Le_LinkIssuer=""
  1208. Le_CertCreateTime=""
  1209. Le_CertCreateTimeStr=""
  1210. Le_RenewalDays=""
  1211. Le_NextRenewTime=""
  1212. Le_NextRenewTimeStr=""
  1213. Le_RealCertPath=""
  1214. Le_RealKeyPath=""
  1215. Le_RealCACertPath=""
  1216. Le_ReloadCmd=""
  1217. Le_RealFullChainPath=""
  1218. DOMAIN_PATH=""
  1219. DOMAIN_CONF=""
  1220. DOMAIN_SSL_CONF=""
  1221. CSR_PATH=""
  1222. CERT_KEY_PATH=""
  1223. CERT_PATH=""
  1224. CA_CERT_PATH=""
  1225. CERT_PFX_PATH=""
  1226. CERT_FULLCHAIN_PATH=""
  1227. ACCOUNT_KEY_PATH=""
  1228. wellknown_path=""
  1229. renew "$d"
  1230. done
  1231. }
  1232. installcert() {
  1233. Le_Domain="$1"
  1234. if [[ -z "$Le_Domain" ]] ; then
  1235. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1236. return 1
  1237. fi
  1238. Le_RealCertPath="$2"
  1239. Le_RealKeyPath="$3"
  1240. Le_RealCACertPath="$4"
  1241. Le_ReloadCmd="$5"
  1242. Le_RealFullChainPath="$6"
  1243. _initpath $Le_Domain
  1244. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1245. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1246. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1247. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1248. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  1249. if [[ "$Le_RealCertPath" ]] ; then
  1250. if [[ -f "$Le_RealCertPath" ]] ; then
  1251. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1252. fi
  1253. cat "$CERT_PATH" > "$Le_RealCertPath"
  1254. fi
  1255. if [[ "$Le_RealCACertPath" ]] ; then
  1256. if [[ "$Le_RealCACertPath" == "$Le_RealCertPath" ]] ; then
  1257. echo "" >> "$Le_RealCACertPath"
  1258. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1259. else
  1260. if [[ -f "$Le_RealCACertPath" ]] ; then
  1261. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1262. fi
  1263. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1264. fi
  1265. fi
  1266. if [[ "$Le_RealKeyPath" ]] ; then
  1267. if [[ -f "$Le_RealKeyPath" ]] ; then
  1268. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1269. fi
  1270. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1271. fi
  1272. if [[ "$Le_RealFullChainPath" ]] ; then
  1273. if [[ -f "$Le_RealFullChainPath" ]] ; then
  1274. cp -p "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1275. fi
  1276. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1277. fi
  1278. if [[ "$Le_ReloadCmd" ]] ; then
  1279. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1280. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1281. fi
  1282. }
  1283. installcronjob() {
  1284. _initpath
  1285. if ! _exists "crontab" ; then
  1286. _err "crontab doesn't exist, so, we can not install cron jobs."
  1287. _err "All your certs will not be renewed automatically."
  1288. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1289. return 1
  1290. fi
  1291. _info "Installing cron job"
  1292. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1293. if [[ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]] ; then
  1294. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1295. else
  1296. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1297. return 1
  1298. fi
  1299. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1300. fi
  1301. if [[ "$?" != "0" ]] ; then
  1302. _err "Install cron job failed. You need to manually renew your certs."
  1303. _err "Or you can add cronjob by yourself:"
  1304. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1305. return 1
  1306. fi
  1307. }
  1308. uninstallcronjob() {
  1309. if ! _exists "crontab" ; then
  1310. return
  1311. fi
  1312. _info "Removing cron job"
  1313. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1314. if [[ "$cr" ]] ; then
  1315. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1316. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1317. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1318. fi
  1319. _initpath
  1320. }
  1321. revoke() {
  1322. Le_Domain="$1"
  1323. if [[ -z "$Le_Domain" ]] ; then
  1324. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1325. return 1
  1326. fi
  1327. _initpath $Le_Domain
  1328. if [[ ! -f "$DOMAIN_CONF" ]] ; then
  1329. _err "$Le_Domain is not a issued domain, skip."
  1330. return 1;
  1331. fi
  1332. if [[ ! -f "$CERT_PATH" ]] ; then
  1333. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1334. return 1
  1335. fi
  1336. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1337. if [[ -z "$cert" ]] ; then
  1338. _err "Cert for $Le_Domain is empty found, skip."
  1339. return 1
  1340. fi
  1341. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1342. uri="$API/acme/revoke-cert"
  1343. _info "Try domain key first."
  1344. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1345. if [[ -z "$response" ]] ; then
  1346. _info "Revoke success."
  1347. rm -f $CERT_PATH
  1348. return 0
  1349. else
  1350. _err "Revoke error by domain key."
  1351. _err "$resource"
  1352. fi
  1353. fi
  1354. _info "Then try account key."
  1355. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1356. if [[ -z "$response" ]] ; then
  1357. _info "Revoke success."
  1358. rm -f $CERT_PATH
  1359. return 0
  1360. else
  1361. _err "Revoke error."
  1362. _debug "$resource"
  1363. fi
  1364. fi
  1365. return 1
  1366. }
  1367. # Detect profile file if not specified as environment variable
  1368. _detect_profile() {
  1369. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1370. echo "$PROFILE"
  1371. return
  1372. fi
  1373. local DETECTED_PROFILE
  1374. DETECTED_PROFILE=''
  1375. local SHELLTYPE
  1376. SHELLTYPE="$(basename "/$SHELL")"
  1377. if [[ "$SHELLTYPE" = "bash" ]] ; then
  1378. if [[ -f "$HOME/.bashrc" ]] ; then
  1379. DETECTED_PROFILE="$HOME/.bashrc"
  1380. elif [[ -f "$HOME/.bash_profile" ]] ; then
  1381. DETECTED_PROFILE="$HOME/.bash_profile"
  1382. fi
  1383. elif [[ "$SHELLTYPE" = "zsh" ]] ; then
  1384. DETECTED_PROFILE="$HOME/.zshrc"
  1385. fi
  1386. if [[ -z "$DETECTED_PROFILE" ]] ; then
  1387. if [[ -f "$HOME/.profile" ]] ; then
  1388. DETECTED_PROFILE="$HOME/.profile"
  1389. elif [[ -f "$HOME/.bashrc" ]] ; then
  1390. DETECTED_PROFILE="$HOME/.bashrc"
  1391. elif [[ -f "$HOME/.bash_profile" ]] ; then
  1392. DETECTED_PROFILE="$HOME/.bash_profile"
  1393. elif [[ -f "$HOME/.zshrc" ]] ; then
  1394. DETECTED_PROFILE="$HOME/.zshrc"
  1395. fi
  1396. fi
  1397. if [[ ! -z "$DETECTED_PROFILE" ]] ; then
  1398. echo "$DETECTED_PROFILE"
  1399. fi
  1400. }
  1401. _initconf() {
  1402. _initpath
  1403. if [[ ! -f "$ACCOUNT_CONF_PATH" ]] ; then
  1404. echo "#ACCOUNT_CONF_PATH=xxxx
  1405. #Account configurations:
  1406. #Here are the supported macros, uncomment them to make them take effect.
  1407. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1408. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1409. #CERT_HOME=\"/path/to/cert/home\"
  1410. #STAGE=1 # Use the staging api
  1411. #FORCE=1 # Force to issue cert
  1412. #DEBUG=1 # Debug mode
  1413. #ACCOUNT_KEY_HASH=account key hash
  1414. USER_AGENT=\"$USER_AGENT\"
  1415. #USER_PATH=""
  1416. #dns api
  1417. #######################
  1418. #Cloudflare:
  1419. #api key
  1420. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1421. #account email
  1422. #CF_Email=\"xxxx@sss.com\"
  1423. #######################
  1424. #Dnspod.cn:
  1425. #api key id
  1426. #DP_Id=\"1234\"
  1427. #api key
  1428. #DP_Key=\"sADDsdasdgdsf\"
  1429. #######################
  1430. #Cloudxns.com:
  1431. #CX_Key=\"1234\"
  1432. #
  1433. #CX_Secret=\"sADDsdasdgdsf\"
  1434. " > $ACCOUNT_CONF_PATH
  1435. fi
  1436. }
  1437. _precheck() {
  1438. if ! _exists "curl" && ! _exists "wget"; then
  1439. _err "Please install curl or wget first, we need to access http resources."
  1440. return 1
  1441. fi
  1442. if ! _exists "crontab" ; then
  1443. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1444. _err "We need to set cron job to renew the certs automatically."
  1445. _err "Otherwise, your certs will not be able to be renewed automatically."
  1446. if [[ -z "$FORCE" ]] ; then
  1447. _err "Please add '--force' and try install again to go without crontab."
  1448. _err "./$PROJECT_ENTRY --install --force"
  1449. return 1
  1450. fi
  1451. fi
  1452. if ! _exists "openssl" ; then
  1453. _err "Please install openssl first."
  1454. _err "We need openssl to generate keys."
  1455. return 1
  1456. fi
  1457. if ! _exists "nc" ; then
  1458. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1459. _err "We use nc for standalone server if you use standalone mode."
  1460. _err "If you don't use standalone mode, just ignore this warning."
  1461. fi
  1462. return 0
  1463. }
  1464. install() {
  1465. if ! _initpath ; then
  1466. _err "Install failed."
  1467. return 1
  1468. fi
  1469. if ! _precheck ; then
  1470. _err "Pre-check failed, can not install."
  1471. return 1
  1472. fi
  1473. #convert from le
  1474. if [[ -d "$HOME/.le" ]] ; then
  1475. for envfile in "le.env" "le.sh.env"
  1476. do
  1477. if [[ -f "$HOME/.le/$envfile" ]] ; then
  1478. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1479. _upgrading="1"
  1480. _info "You are upgrading from le.sh"
  1481. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1482. mv "$HOME/.le" "$LE_WORKING_DIR"
  1483. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1484. break;
  1485. fi
  1486. fi
  1487. done
  1488. fi
  1489. _info "Installing to $LE_WORKING_DIR"
  1490. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1491. _err "Can not craete working dir: $LE_WORKING_DIR"
  1492. return 1
  1493. fi
  1494. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1495. if [[ "$?" != "0" ]] ; then
  1496. _err "Install failed, can not copy $PROJECT_ENTRY"
  1497. return 1
  1498. fi
  1499. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1500. _profile="$(_detect_profile)"
  1501. if [[ "$_profile" ]] ; then
  1502. _debug "Found profile: $_profile"
  1503. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1504. if [[ "$_upgrading" == "1" ]] ; then
  1505. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1506. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1507. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1508. fi
  1509. _setopt "$_envfile" "LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1510. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1511. echo "" >> "$_profile"
  1512. _setopt "$_profile" "source \"$LE_WORKING_DIR/$PROJECT_NAME.env\""
  1513. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1514. else
  1515. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1516. fi
  1517. mkdir -p $LE_WORKING_DIR/dnsapi
  1518. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1519. #to keep compatible mv the .acc file to .key file
  1520. if [[ -f "$LE_WORKING_DIR/account.acc" ]] ; then
  1521. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1522. fi
  1523. if [[ ! -f "$ACCOUNT_CONF_PATH" ]] ; then
  1524. _initconf
  1525. fi
  1526. if [[ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]] ; then
  1527. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1528. fi
  1529. if [[ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]] ; then
  1530. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1531. fi
  1532. if [[ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]] ; then
  1533. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1534. fi
  1535. installcronjob
  1536. _info OK
  1537. }
  1538. uninstall() {
  1539. uninstallcronjob
  1540. _initpath
  1541. _profile="$(_detect_profile)"
  1542. if [[ "$_profile" ]] ; then
  1543. text="$(cat $_profile)"
  1544. echo "$text" | sed "s|^source.*$PROJECT_NAME.env.*$||" > "$_profile"
  1545. fi
  1546. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1547. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1548. }
  1549. cron() {
  1550. IN_CRON=1
  1551. renewAll
  1552. IN_CRON=""
  1553. }
  1554. version() {
  1555. echo "$PROJECT"
  1556. echo "v$VER"
  1557. }
  1558. showhelp() {
  1559. version
  1560. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1561. Commands:
  1562. --help, -h Show this help message.
  1563. --version, -v Show version info.
  1564. --install Install $PROJECT_NAME to your system.
  1565. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1566. --issue Issue a cert.
  1567. --installcert Install the issued cert to apache/nginx or any other server.
  1568. --renew, -r Renew a cert.
  1569. --renewAll Renew all the certs
  1570. --revoke Revoke a cert.
  1571. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1572. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1573. --cron Run cron job to renew all the certs.
  1574. --toPkcs Export the certificate and key to a pfx file.
  1575. --createAccountKey, -cak Create an account private key, professional use.
  1576. --createDomainKey, -cdk Create an domain private key, professional use.
  1577. --createCSR, -ccsr Create CSR , professional use.
  1578. Parameters:
  1579. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1580. --force, -f Used to force to install or force to renew a cert immediately.
  1581. --staging, --test Use staging server, just for test.
  1582. --debug Output debug info.
  1583. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1584. --standalone Use standalone mode.
  1585. --apache Use apache mode.
  1586. --dns [dns-cf|dns-dp|dns-cx|/path/to/api/file] Use dns mode or dns api.
  1587. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1588. --accountkeylength, -ak [2048] Specifies the account key length.
  1589. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1590. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1591. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1592. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1593. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1594. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1595. --accountconf Specifies a customized account config file.
  1596. --home Specifies the home dir for $PROJECT_NAME .
  1597. --certhome Specifies the home dir to save all the certs.
  1598. --useragent Specifies the user agent string. it will be saved for future use too.
  1599. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1600. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1601. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1602. "
  1603. }
  1604. _installOnline() {
  1605. _info "Installing from online archive."
  1606. if [[ ! "$BRANCH" ]] ; then
  1607. BRANCH="master"
  1608. fi
  1609. _initpath
  1610. target="$PROJECT/archive/$BRANCH.tar.gz"
  1611. _info "Downloading $target"
  1612. localname="$BRANCH.tar.gz"
  1613. if ! _get "$target" > $localname ; then
  1614. _debug "Download error."
  1615. return 1
  1616. fi
  1617. _info "Extracting $localname"
  1618. tar xzf $localname
  1619. cd "$PROJECT_NAME-$BRANCH"
  1620. chmod +x $PROJECT_ENTRY
  1621. if ./$PROJECT_ENTRY install ; then
  1622. _info "Install success!"
  1623. fi
  1624. cd ..
  1625. rm -rf "$PROJECT_NAME-$BRANCH"
  1626. rm -f "$localname"
  1627. }
  1628. _process() {
  1629. _CMD=""
  1630. _domain=""
  1631. _altdomains="no"
  1632. _webroot=""
  1633. _keylength="no"
  1634. _accountkeylength="no"
  1635. _certpath="no"
  1636. _keypath="no"
  1637. _capath="no"
  1638. _fullchainpath="no"
  1639. _reloadcmd="no"
  1640. _password=""
  1641. _accountconf=""
  1642. _useragent=""
  1643. _accountemail=""
  1644. _accountkey=""
  1645. _certhome=""
  1646. while (( ${#} )); do
  1647. case "${1}" in
  1648. --help|-h)
  1649. showhelp
  1650. return
  1651. ;;
  1652. --version|-v)
  1653. version
  1654. return
  1655. ;;
  1656. --install)
  1657. _CMD="install"
  1658. ;;
  1659. --uninstall)
  1660. _CMD="uninstall"
  1661. ;;
  1662. --issue)
  1663. _CMD="issue"
  1664. ;;
  1665. --installcert|-i)
  1666. _CMD="installcert"
  1667. ;;
  1668. --renew|-r)
  1669. _CMD="renew"
  1670. ;;
  1671. --renewAll|-renewall)
  1672. _CMD="renewAll"
  1673. ;;
  1674. --revoke)
  1675. _CMD="revoke"
  1676. ;;
  1677. --installcronjob)
  1678. _CMD="installcronjob"
  1679. ;;
  1680. --uninstallcronjob)
  1681. _CMD="uninstallcronjob"
  1682. ;;
  1683. --cron)
  1684. _CMD="cron"
  1685. ;;
  1686. --toPkcs)
  1687. _CMD="toPkcs"
  1688. ;;
  1689. --createAccountKey|--createaccountkey|-cak)
  1690. _CMD="createAccountKey"
  1691. ;;
  1692. --createDomainKey|--createdomainkey|-cdk)
  1693. _CMD="createDomainKey"
  1694. ;;
  1695. --createCSR|--createcsr|-ccr)
  1696. _CMD="createCSR"
  1697. ;;
  1698. --domain|-d)
  1699. _dvalue="$2"
  1700. if [[ -z "$_dvalue" ]] || [[ "$_dvalue" == "-"* ]] ; then
  1701. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1702. return 1
  1703. fi
  1704. if [[ -z "$_domain" ]] ; then
  1705. _domain="$_dvalue"
  1706. else
  1707. if [[ "$_altdomains" == "no" ]] ; then
  1708. _altdomains="$_dvalue"
  1709. else
  1710. _altdomains="$_altdomains,$_dvalue"
  1711. fi
  1712. fi
  1713. shift
  1714. ;;
  1715. --force|-f)
  1716. FORCE="1"
  1717. ;;
  1718. --staging|--test)
  1719. STAGE="1"
  1720. ;;
  1721. --debug)
  1722. if [[ "$2" == "-"* ]] || [[ -z "$2" ]]; then
  1723. DEBUG="1"
  1724. else
  1725. DEBUG="$2"
  1726. shift
  1727. fi
  1728. ;;
  1729. --webroot|-w)
  1730. wvalue="$2"
  1731. if [[ -z "$_webroot" ]] ; then
  1732. _webroot="$wvalue"
  1733. else
  1734. _webroot="$_webroot,$wvalue"
  1735. fi
  1736. shift
  1737. ;;
  1738. --standalone)
  1739. wvalue="no"
  1740. if [[ -z "$_webroot" ]] ; then
  1741. _webroot="$wvalue"
  1742. else
  1743. _webroot="$_webroot,$wvalue"
  1744. fi
  1745. ;;
  1746. --apache)
  1747. wvalue="apache"
  1748. if [[ -z "$_webroot" ]] ; then
  1749. _webroot="$wvalue"
  1750. else
  1751. _webroot="$_webroot,$wvalue"
  1752. fi
  1753. ;;
  1754. --dns)
  1755. wvalue="dns"
  1756. if [[ "$2" != "-"* ]] ; then
  1757. wvalue="$2"
  1758. shift
  1759. fi
  1760. if [[ -z "$_webroot" ]] ; then
  1761. _webroot="$wvalue"
  1762. else
  1763. _webroot="$_webroot,$wvalue"
  1764. fi
  1765. ;;
  1766. --keylength|-k)
  1767. _keylength="$2"
  1768. accountkeylength="$2"
  1769. shift
  1770. ;;
  1771. --accountkeylength|-ak)
  1772. accountkeylength="$2"
  1773. shift
  1774. ;;
  1775. --certpath)
  1776. _certpath="$2"
  1777. shift
  1778. ;;
  1779. --keypath)
  1780. _keypath="$2"
  1781. shift
  1782. ;;
  1783. --capath)
  1784. _capath="$2"
  1785. shift
  1786. ;;
  1787. --fullchainpath)
  1788. _fullchainpath="$2"
  1789. shift
  1790. ;;
  1791. --reloadcmd|--reloadCmd)
  1792. _reloadcmd="$2"
  1793. shift
  1794. ;;
  1795. --password)
  1796. _password="$2"
  1797. shift
  1798. ;;
  1799. --accountconf)
  1800. _accountconf="$2"
  1801. ACCOUNT_CONF_PATH="$_accountconf"
  1802. shift
  1803. ;;
  1804. --home)
  1805. LE_WORKING_DIR="$2"
  1806. shift
  1807. ;;
  1808. --certhome)
  1809. _certhome="$2"
  1810. CERT_HOME="$_certhome"
  1811. shift
  1812. ;;
  1813. --useragent)
  1814. _useragent="$2"
  1815. USER_AGENT="$_useragent"
  1816. shift
  1817. ;;
  1818. --accountemail )
  1819. _accountemail="$2"
  1820. ACCOUNT_EMAIL="$_accountemail"
  1821. shift
  1822. ;;
  1823. --accountkey )
  1824. _accountkey="$2"
  1825. ACCOUNT_KEY_PATH="$_accountkey"
  1826. shift
  1827. ;;
  1828. --days )
  1829. _days="$2"
  1830. Le_RenewalDays="$_days"
  1831. shift
  1832. ;;
  1833. *)
  1834. _err "Unknown parameter : $1"
  1835. return 1
  1836. ;;
  1837. esac
  1838. shift 1
  1839. done
  1840. case "${_CMD}" in
  1841. install) install ;;
  1842. uninstall) uninstall ;;
  1843. issue)
  1844. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1845. ;;
  1846. installcert)
  1847. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1848. ;;
  1849. renew)
  1850. renew "$_domain"
  1851. ;;
  1852. renewAll)
  1853. renewAll
  1854. ;;
  1855. revoke)
  1856. revoke "$_domain"
  1857. ;;
  1858. installcronjob) installcronjob ;;
  1859. uninstallcronjob) uninstallcronjob ;;
  1860. cron) cron ;;
  1861. toPkcs)
  1862. toPkcs "$_domain" "$_password"
  1863. ;;
  1864. createAccountKey)
  1865. createAccountKey "$_domain" "$_accountkeylength"
  1866. ;;
  1867. createDomainKey)
  1868. createDomainKey "$_domain" "$_keylength"
  1869. ;;
  1870. createCSR)
  1871. createCSR "$_domain" "$_altdomains"
  1872. ;;
  1873. *)
  1874. _err "Invalid command: $_CMD"
  1875. showhelp;
  1876. return 1
  1877. ;;
  1878. esac
  1879. if [[ "$_useragent" ]] ; then
  1880. _saveaccountconf "USER_AGENT" "$_useragent"
  1881. fi
  1882. if [[ "$_accountemail" ]] ; then
  1883. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  1884. fi
  1885. }
  1886. if [[ "$INSTALLONLINE" ]] ; then
  1887. INSTALLONLINE=""
  1888. _installOnline $BRANCH
  1889. exit
  1890. fi
  1891. if [[ -z "$1" ]] ; then
  1892. showhelp
  1893. else
  1894. if [[ "$1" == "-"* ]] ; then
  1895. _process "$@"
  1896. else
  1897. "$@"
  1898. fi
  1899. fi